diff --git a/sync-for-payables/RELEASES.md b/sync-for-payables/RELEASES.md index d4c90b866..18c03cc37 100644 --- a/sync-for-payables/RELEASES.md +++ b/sync-for-payables/RELEASES.md @@ -118,4 +118,14 @@ Based on: ### Generated - [python v9.1.0] sync-for-payables ### Releases -- [PyPI v9.1.0] https://pypi.org/project/codat-sync-for-payables/9.1.0 - sync-for-payables \ No newline at end of file +- [PyPI v9.1.0] https://pypi.org/project/codat-sync-for-payables/9.1.0 - sync-for-payables + +## 2026-08-07 11:55:26 +### Changes +Based on: +- OpenAPI Doc 3.0.0 https://raw.githubusercontent.com/codatio/oas/main/yaml/Codat-Sync-Payables.yaml +- codat sdk-codegen b5f25135143b1ccfb99c941df11a7a1596dbe31e https://github.com/codat-spikes/sdk-codegen +### Generated +- [python v9.1.1] sync-for-payables +### Releases +- [PyPI v9.1.1] https://pypi.org/project/codat-sync-for-payables/9.1.1 - sync-for-payables diff --git a/sync-for-payables/USAGE.md b/sync-for-payables/USAGE.md index 4e0078b54..0f3755858 100644 --- a/sync-for-payables/USAGE.md +++ b/sync-for-payables/USAGE.md @@ -1,53 +1,53 @@ - -```python -# Synchronous Example -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.companies.list(request={ - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - "order_by": "-modifiedDate", - "tags": "region=uk && team=invoice-finance", - }) - - # Handle response - print(res) -``` - -
- -The same SDK client can also be used to make asynchronous requests by importing asyncio. - -```python -# Asynchronous Example -import asyncio -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - -async def main(): - - async with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), - ) as codat_sync_payables: - - res = await codat_sync_payables.companies.list_async(request={ - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - "order_by": "-modifiedDate", - "tags": "region=uk && team=invoice-finance", - }) - - # Handle response - print(res) - -asyncio.run(main()) -``` + +```python +# Synchronous Example +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.companies.list(request={ + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + "order_by": "-modifiedDate", + "tags": "region=uk && team=invoice-finance", + }) + + # Handle response + print(res) +``` + +
+ +The same SDK client can also be used to make asynchronous requests by importing asyncio. + +```python +# Asynchronous Example +import asyncio +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + +async def main(): + + async with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), + ) as codat_sync_payables: + + res = await codat_sync_payables.companies.list_async(request={ + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + "order_by": "-modifiedDate", + "tags": "region=uk && team=invoice-finance", + }) + + # Handle response + print(res) + +asyncio.run(main()) +``` \ No newline at end of file diff --git a/sync-for-payables/docs/models/errors/errormessage.md b/sync-for-payables/docs/models/errors/errormessage.md index 752db0013..425e22bbf 100644 --- a/sync-for-payables/docs/models/errors/errormessage.md +++ b/sync-for-payables/docs/models/errors/errormessage.md @@ -1,16 +1,14 @@ -# ErrorMessage - -Your `query` parameter was not correctly formed - - -## Fields - -| Field | Type | Required | Description | -| ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `status_code` | *Optional[int]* | :heavy_minus_sign: | The HTTP status code returned by the error. | -| `service` | *Optional[str]* | :heavy_minus_sign: | Codat's service the returned the error. | -| `error` | *Optional[str]* | :heavy_minus_sign: | A brief description of the error. | -| `correlation_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier used to propagate to all downstream services and determine the source of the error. | -| `validation` | [OptionalNullable[shared.ErrorValidation]](../../models/shared/errorvalidation.md) | :heavy_minus_sign: | A human-readable object describing validation decisions Codat has made. If an operation has failed because of validation errors, they will be detailed here. | -| `can_be_retried` | *Optional[str]* | :heavy_minus_sign: | `True` if the error occurred transiently and can be retried. | -| `detailed_error_code` | *Optional[int]* | :heavy_minus_sign: | Machine readable error code used to automate processes based on the code returned. | \ No newline at end of file +# ErrorMessage + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `can_be_retried` | *Optional[str]* | :heavy_minus_sign: | `True` if the error occurred transiently and can be retried. | +| `correlation_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier used to propagate to all downstream services and determine the source of the error. | +| `detailed_error_code` | *Optional[int]* | :heavy_minus_sign: | Machine readable error code used to automate processes based on the code returned. | +| `error` | *Optional[str]* | :heavy_minus_sign: | A brief description of the error. | +| `service` | *Optional[str]* | :heavy_minus_sign: | Codat's service the returned the error. | +| `status_code` | *Optional[int]* | :heavy_minus_sign: | The HTTP status code returned by the error. | +| `validation` | [Optional[shared.ErrorValidation]](../../models/shared/errorvalidation.md) | :heavy_minus_sign: | A human-readable object describing validation decisions Codat has made. If an operation has failed because of validation errors, they will be detailed here. | \ No newline at end of file diff --git a/sync-for-payables/docs/models/operations/createbankaccountrequest.md b/sync-for-payables/docs/models/operations/createbankaccountrequest.md index 3a74ffd7c..b9f376932 100644 --- a/sync-for-payables/docs/models/operations/createbankaccountrequest.md +++ b/sync-for-payables/docs/models/operations/createbankaccountrequest.md @@ -1,11 +1,11 @@ -# CreateBankAccountRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | -| `idempotency_key` | *Optional[str]* | :heavy_minus_sign: | A unique identifier to ensure idempotent behaviour for subsequent requests. | | -| `bank_account_prototype` | [Optional[shared.BankAccountPrototype]](../../models/shared/bankaccountprototype.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file +# CreateBankAccountRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | +| `bank_account_prototype` | [Optional[shared.BankAccountPrototype]](../../models/shared/bankaccountprototype.md) | :heavy_minus_sign: | N/A | | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | +| `idempotency_key` | *Optional[str]* | :heavy_minus_sign: | A unique identifier to ensure idempotent behaviour for subsequent requests. | | \ No newline at end of file diff --git a/sync-for-payables/docs/models/operations/createbillpaymentrequest.md b/sync-for-payables/docs/models/operations/createbillpaymentrequest.md index d5bd37b70..d6f2073c8 100644 --- a/sync-for-payables/docs/models/operations/createbillpaymentrequest.md +++ b/sync-for-payables/docs/models/operations/createbillpaymentrequest.md @@ -1,12 +1,12 @@ -# CreateBillPaymentRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | -| `bill_id` | *str* | :heavy_check_mark: | Unique identifier for a bill. | **Example 1:** 13d946f0-c5d5-42bc-b092-97ece17923ab
**Example 2:** 9wg4lep4ush5cxs79pl8sozmsndbaukll3ind4g7buqbm1h2
**Example 3:** 7110701885
**Example 4:** EILBDVJVNUAGVKRQ | -| `idempotency_key` | *Optional[str]* | :heavy_minus_sign: | A unique identifier to ensure idempotent behaviour for subsequent requests. | | -| `bill_payment_prototype` | [Optional[shared.BillPaymentPrototype]](../../models/shared/billpaymentprototype.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file +# CreateBillPaymentRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `bill_id` | *str* | :heavy_check_mark: | Unique identifier for a bill. | **Example 1:** 13d946f0-c5d5-42bc-b092-97ece17923ab
**Example 2:** 9wg4lep4ush5cxs79pl8sozmsndbaukll3ind4g7buqbm1h2
**Example 3:** 7110701885
**Example 4:** EILBDVJVNUAGVKRQ | +| `bill_payment_prototype` | [Optional[shared.BillPaymentPrototype]](../../models/shared/billpaymentprototype.md) | :heavy_minus_sign: | N/A | | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | +| `idempotency_key` | *Optional[str]* | :heavy_minus_sign: | A unique identifier to ensure idempotent behaviour for subsequent requests. | | \ No newline at end of file diff --git a/sync-for-payables/docs/models/operations/createbillrequest.md b/sync-for-payables/docs/models/operations/createbillrequest.md index 6b83a39bc..f953c6b94 100644 --- a/sync-for-payables/docs/models/operations/createbillrequest.md +++ b/sync-for-payables/docs/models/operations/createbillrequest.md @@ -1,11 +1,11 @@ -# CreateBillRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| --------------------------------------------------------------------------- | --------------------------------------------------------------------------- | --------------------------------------------------------------------------- | --------------------------------------------------------------------------- | --------------------------------------------------------------------------- | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | -| `idempotency_key` | *Optional[str]* | :heavy_minus_sign: | A unique identifier to ensure idempotent behaviour for subsequent requests. | | -| `bill_prototype` | [Optional[shared.BillPrototype]](../../models/shared/billprototype.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file +# CreateBillRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------------------------------------------------------- | --------------------------------------------------------------------------- | --------------------------------------------------------------------------- | --------------------------------------------------------------------------- | --------------------------------------------------------------------------- | +| `bill_prototype` | [Optional[shared.BillPrototype]](../../models/shared/billprototype.md) | :heavy_minus_sign: | N/A | | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | +| `idempotency_key` | *Optional[str]* | :heavy_minus_sign: | A unique identifier to ensure idempotent behaviour for subsequent requests. | | \ No newline at end of file diff --git a/sync-for-payables/docs/models/operations/createcompanyrequest.md b/sync-for-payables/docs/models/operations/createcompanyrequest.md new file mode 100644 index 000000000..ebd7ca0a0 --- /dev/null +++ b/sync-for-payables/docs/models/operations/createcompanyrequest.md @@ -0,0 +1,8 @@ +# CreateCompanyRequest + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | +| `company_request_body` | [Optional[shared.CompanyRequestBody]](../../models/shared/companyrequestbody.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/sync-for-payables/docs/models/operations/createconnectionrequest.md b/sync-for-payables/docs/models/operations/createconnectionrequest.md index ff26e52b6..32316fd7b 100644 --- a/sync-for-payables/docs/models/operations/createconnectionrequest.md +++ b/sync-for-payables/docs/models/operations/createconnectionrequest.md @@ -1,9 +1,9 @@ -# CreateConnectionRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `request_body` | [Optional[operations.CreateConnectionRequestBody]](../../models/operations/createconnectionrequestbody.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file +# CreateConnectionRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | +| `request_body` | [Optional[operations.CreateConnectionRequestBody]](../../models/operations/createconnectionrequestbody.md) | :heavy_minus_sign: | N/A | | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | \ No newline at end of file diff --git a/sync-for-payables/docs/models/operations/createconnectionrequestbody.md b/sync-for-payables/docs/models/operations/createconnectionrequestbody.md index 891314d08..5a6200d18 100644 --- a/sync-for-payables/docs/models/operations/createconnectionrequestbody.md +++ b/sync-for-payables/docs/models/operations/createconnectionrequestbody.md @@ -1,8 +1,8 @@ -# CreateConnectionRequestBody - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `platform_key` | *Optional[str]* | :heavy_minus_sign: | A unique 4-letter key to represent a platform in each integration. View [accounting](https://docs.codat.io/integrations/accounting/overview#platform-keys), [banking](https://docs.codat.io/integrations/banking/overview#platform-keys), and [commerce](https://docs.codat.io/integrations/commerce/overview#platform-keys) platform keys. | gbol | \ No newline at end of file +# CreateConnectionRequestBody + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `platform_key` | *Optional[str]* | :heavy_minus_sign: | A unique 4-letter key to represent a platform in each integration. View [accounting](https://docs.codat.io/integrations/accounting/overview#platform-keys), [banking](https://docs.codat.io/integrations/banking/overview#platform-keys), and [commerce](https://docs.codat.io/integrations/commerce/overview#platform-keys) platform keys. | \ No newline at end of file diff --git a/sync-for-payables/docs/models/operations/createsupplierrequest.md b/sync-for-payables/docs/models/operations/createsupplierrequest.md index b820d5d6f..e1c8bd704 100644 --- a/sync-for-payables/docs/models/operations/createsupplierrequest.md +++ b/sync-for-payables/docs/models/operations/createsupplierrequest.md @@ -1,11 +1,11 @@ -# CreateSupplierRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | -| `idempotency_key` | *Optional[str]* | :heavy_minus_sign: | A unique identifier to ensure idempotent behaviour for subsequent requests. | | +# CreateSupplierRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | +| `idempotency_key` | *Optional[str]* | :heavy_minus_sign: | A unique identifier to ensure idempotent behaviour for subsequent requests. | | | `supplier_prototype` | [Optional[shared.SupplierPrototype]](../../models/shared/supplierprototype.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/sync-for-payables/docs/models/operations/deletecompanyrequest.md b/sync-for-payables/docs/models/operations/deletecompanyrequest.md index 338ee40e5..6f16204ca 100644 --- a/sync-for-payables/docs/models/operations/deletecompanyrequest.md +++ b/sync-for-payables/docs/models/operations/deletecompanyrequest.md @@ -1,8 +1,8 @@ -# DeleteCompanyRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +# DeleteCompanyRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | | `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | \ No newline at end of file diff --git a/sync-for-payables/docs/models/operations/deleteconnectionrequest.md b/sync-for-payables/docs/models/operations/deleteconnectionrequest.md index 9650dc387..f4b0d4cb4 100644 --- a/sync-for-payables/docs/models/operations/deleteconnectionrequest.md +++ b/sync-for-payables/docs/models/operations/deleteconnectionrequest.md @@ -1,9 +1,9 @@ -# DeleteConnectionRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +# DeleteConnectionRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | | `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | \ No newline at end of file diff --git a/sync-for-payables/docs/models/operations/downloadbillattachmentrequest.md b/sync-for-payables/docs/models/operations/downloadbillattachmentrequest.md index 2df731fdb..607ff8756 100644 --- a/sync-for-payables/docs/models/operations/downloadbillattachmentrequest.md +++ b/sync-for-payables/docs/models/operations/downloadbillattachmentrequest.md @@ -1,11 +1,11 @@ -# DownloadBillAttachmentRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | -| `bill_id` | *str* | :heavy_check_mark: | Unique identifier for a bill. | **Example 1:** 13d946f0-c5d5-42bc-b092-97ece17923ab
**Example 2:** 9wg4lep4ush5cxs79pl8sozmsndbaukll3ind4g7buqbm1h2
**Example 3:** 7110701885
**Example 4:** EILBDVJVNUAGVKRQ | -| `attachment_id` | *str* | :heavy_check_mark: | Unique identifier for an attachment. | 8a210b68-6988-11ed-a1eb-0242ac120002 | \ No newline at end of file +# DownloadBillAttachmentRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `attachment_id` | *str* | :heavy_check_mark: | Unique identifier for an attachment. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `bill_id` | *str* | :heavy_check_mark: | Unique identifier for a bill. | **Example 1:** 13d946f0-c5d5-42bc-b092-97ece17923ab
**Example 2:** 9wg4lep4ush5cxs79pl8sozmsndbaukll3ind4g7buqbm1h2
**Example 3:** 7110701885
**Example 4:** EILBDVJVNUAGVKRQ | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | \ No newline at end of file diff --git a/sync-for-payables/docs/models/operations/getcompanyinformationrequest.md b/sync-for-payables/docs/models/operations/getcompanyinformationrequest.md index 657eb5cde..850e223d8 100644 --- a/sync-for-payables/docs/models/operations/getcompanyinformationrequest.md +++ b/sync-for-payables/docs/models/operations/getcompanyinformationrequest.md @@ -1,9 +1,9 @@ -# GetCompanyInformationRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +# GetCompanyInformationRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | | `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | \ No newline at end of file diff --git a/sync-for-payables/docs/models/operations/getcompanyrequest.md b/sync-for-payables/docs/models/operations/getcompanyrequest.md index 240b811b6..295378c0b 100644 --- a/sync-for-payables/docs/models/operations/getcompanyrequest.md +++ b/sync-for-payables/docs/models/operations/getcompanyrequest.md @@ -1,8 +1,8 @@ -# GetCompanyRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +# GetCompanyRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | | `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | \ No newline at end of file diff --git a/sync-for-payables/docs/models/operations/getconnectionrequest.md b/sync-for-payables/docs/models/operations/getconnectionrequest.md index 6e9f3d18b..61c906783 100644 --- a/sync-for-payables/docs/models/operations/getconnectionrequest.md +++ b/sync-for-payables/docs/models/operations/getconnectionrequest.md @@ -1,9 +1,9 @@ -# GetConnectionRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +# GetConnectionRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | | `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | \ No newline at end of file diff --git a/sync-for-payables/docs/models/operations/getmappingoptionsbillsrequest.md b/sync-for-payables/docs/models/operations/getmappingoptionsbillsrequest.md index 901f6cec7..bfb6f282a 100644 --- a/sync-for-payables/docs/models/operations/getmappingoptionsbillsrequest.md +++ b/sync-for-payables/docs/models/operations/getmappingoptionsbillsrequest.md @@ -1,11 +1,11 @@ -# GetMappingOptionsBillsRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | -| `continuation_token` | *Optional[str]* | :heavy_minus_sign: | Retrieve the next page of results using the continuation token from the previous response. | continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ== | +# GetMappingOptionsBillsRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | +| `continuation_token` | *Optional[str]* | :heavy_minus_sign: | Retrieve the next page of results using the continuation token from the previous response. | continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ== | | `status_query` | *Optional[str]* | :heavy_minus_sign: | Codat query string allows you to filter by `status` (`status=Active\|\|status=Archived`). [Learn more](https://docs.codat.io/using-the-api/querying) about Codat's query string. | status=Archived | \ No newline at end of file diff --git a/sync-for-payables/docs/models/operations/getmappingoptionspaymentsrequest.md b/sync-for-payables/docs/models/operations/getmappingoptionspaymentsrequest.md index 3ae09265f..870456755 100644 --- a/sync-for-payables/docs/models/operations/getmappingoptionspaymentsrequest.md +++ b/sync-for-payables/docs/models/operations/getmappingoptionspaymentsrequest.md @@ -1,11 +1,11 @@ -# GetMappingOptionsPaymentsRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | -| `continuation_token` | *Optional[str]* | :heavy_minus_sign: | Retrieve the next page of results using the continuation token from the previous response. | continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ== | +# GetMappingOptionsPaymentsRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | +| `continuation_token` | *Optional[str]* | :heavy_minus_sign: | Retrieve the next page of results using the continuation token from the previous response. | continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ== | | `status_query` | *Optional[str]* | :heavy_minus_sign: | Codat query string allows you to filter by `status` (`status=Active\|\|status=Archived`). [Learn more](https://docs.codat.io/using-the-api/querying) about Codat's query string. | status=Archived | \ No newline at end of file diff --git a/sync-for-payables/docs/models/operations/listbillattachmentsrequest.md b/sync-for-payables/docs/models/operations/listbillattachmentsrequest.md index 2a271d2fc..7aac29732 100644 --- a/sync-for-payables/docs/models/operations/listbillattachmentsrequest.md +++ b/sync-for-payables/docs/models/operations/listbillattachmentsrequest.md @@ -1,10 +1,10 @@ -# ListBillAttachmentsRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | -| `bill_id` | *str* | :heavy_check_mark: | Unique identifier for a bill. | **Example 1:** 13d946f0-c5d5-42bc-b092-97ece17923ab
**Example 2:** 9wg4lep4ush5cxs79pl8sozmsndbaukll3ind4g7buqbm1h2
**Example 3:** 7110701885
**Example 4:** EILBDVJVNUAGVKRQ | \ No newline at end of file +# ListBillAttachmentsRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `bill_id` | *str* | :heavy_check_mark: | Unique identifier for a bill. | **Example 1:** 13d946f0-c5d5-42bc-b092-97ece17923ab
**Example 2:** 9wg4lep4ush5cxs79pl8sozmsndbaukll3ind4g7buqbm1h2
**Example 3:** 7110701885
**Example 4:** EILBDVJVNUAGVKRQ | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | \ No newline at end of file diff --git a/sync-for-payables/docs/models/operations/listbillsrequest.md b/sync-for-payables/docs/models/operations/listbillsrequest.md index cd5209d7e..5a29c14a0 100644 --- a/sync-for-payables/docs/models/operations/listbillsrequest.md +++ b/sync-for-payables/docs/models/operations/listbillsrequest.md @@ -1,11 +1,11 @@ -# ListBillsRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | -| `continuation_token` | *Optional[str]* | :heavy_minus_sign: | Retrieve the next page of results using the continuation token from the previous response. | continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ== | +# ListBillsRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | +| `continuation_token` | *Optional[str]* | :heavy_minus_sign: | Retrieve the next page of results using the continuation token from the previous response. | continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ== | | `query` | *Optional[str]* | :heavy_minus_sign: | Codat query string allows you to filter by `status` and `sourceModifiedDate`. Learn more about Codat's query string [here](https://docs.codat.io/using-the-api/querying). Platfrom specfic statuses: Xero supports Open \| PartiallyPaid \| Paid \| Void \| Draft. Qbo supports Open \| PartiallyPaid \| Paid. FreeAgent supports Open \| PartiallyPaid \| Paid. | | \ No newline at end of file diff --git a/sync-for-payables/docs/models/operations/listcompaniesrequest.md b/sync-for-payables/docs/models/operations/listcompaniesrequest.md index 8617ea281..e43853f9f 100644 --- a/sync-for-payables/docs/models/operations/listcompaniesrequest.md +++ b/sync-for-payables/docs/models/operations/listcompaniesrequest.md @@ -1,12 +1,12 @@ -# ListCompaniesRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `page` | *Optional[int]* | :heavy_minus_sign: | Page number. [Read more](https://docs.codat.io/using-the-api/paging). | 1 | -| `page_size` | *Optional[int]* | :heavy_minus_sign: | Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging). | 100 | -| `query` | *Optional[str]* | :heavy_minus_sign: | Codat query string. [Read more](https://docs.codat.io/using-the-api/querying). | id=e3334455-1aed-4e71-ab43-6bccf12092ee | -| `order_by` | *Optional[str]* | :heavy_minus_sign: | Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results). | -modifiedDate | +# ListCompaniesRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `order_by` | *Optional[str]* | :heavy_minus_sign: | Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results). | -modifiedDate | +| `page` | *Optional[int]* | :heavy_minus_sign: | Page number. [Read more](https://docs.codat.io/using-the-api/paging). | 1 | +| `page_size` | *Optional[int]* | :heavy_minus_sign: | Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging). | 100 | +| `query` | *Optional[str]* | :heavy_minus_sign: | Codat query string. [Read more](https://docs.codat.io/using-the-api/querying). | id=e3334455-1aed-4e71-ab43-6bccf12092ee | | `tags` | *Optional[str]* | :heavy_minus_sign: | Filter companies by tags using the "equals" (=), "not equals" (!=), and "contains" (~) operators with [Codat’s query language](https://docs.codat.io/using-the-api/querying). | region=uk && team=invoice-finance | \ No newline at end of file diff --git a/sync-for-payables/docs/models/operations/listconnectionsrequest.md b/sync-for-payables/docs/models/operations/listconnectionsrequest.md index 1d852c6cd..0a3173fc6 100644 --- a/sync-for-payables/docs/models/operations/listconnectionsrequest.md +++ b/sync-for-payables/docs/models/operations/listconnectionsrequest.md @@ -1,12 +1,12 @@ -# ListConnectionsRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `page` | *Optional[int]* | :heavy_minus_sign: | Page number. [Read more](https://docs.codat.io/using-the-api/paging). | 1 | -| `page_size` | *Optional[int]* | :heavy_minus_sign: | Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging). | 100 | -| `query` | *Optional[str]* | :heavy_minus_sign: | Codat query string. [Read more](https://docs.codat.io/using-the-api/querying). | id=e3334455-1aed-4e71-ab43-6bccf12092ee | -| `order_by` | *Optional[str]* | :heavy_minus_sign: | Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results). | -modifiedDate | \ No newline at end of file +# ListConnectionsRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `order_by` | *Optional[str]* | :heavy_minus_sign: | Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results). | -modifiedDate | +| `page` | *Optional[int]* | :heavy_minus_sign: | Page number. [Read more](https://docs.codat.io/using-the-api/paging). | 1 | +| `page_size` | *Optional[int]* | :heavy_minus_sign: | Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging). | 100 | +| `query` | *Optional[str]* | :heavy_minus_sign: | Codat query string. [Read more](https://docs.codat.io/using-the-api/querying). | id=e3334455-1aed-4e71-ab43-6bccf12092ee | \ No newline at end of file diff --git a/sync-for-payables/docs/models/operations/listsuppliersrequest.md b/sync-for-payables/docs/models/operations/listsuppliersrequest.md index faf0d748f..b3c034972 100644 --- a/sync-for-payables/docs/models/operations/listsuppliersrequest.md +++ b/sync-for-payables/docs/models/operations/listsuppliersrequest.md @@ -1,11 +1,11 @@ -# ListSuppliersRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | -| `continuation_token` | *Optional[str]* | :heavy_minus_sign: | Retrieve the next page of results using the continuation token from the previous response. | continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ== | +# ListSuppliersRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | +| `continuation_token` | *Optional[str]* | :heavy_minus_sign: | Retrieve the next page of results using the continuation token from the previous response. | continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ== | | `query` | *Optional[str]* | :heavy_minus_sign: | Codat query string allows you to filter by `sourceModifiedDate` or if a supplier is `Active` or `Archived` in the accounting software. Learn more about Codat's query string [here](https://docs.codat.io/using-the-api/querying). | | \ No newline at end of file diff --git a/sync-for-payables/docs/models/operations/replacecompanyrequest.md b/sync-for-payables/docs/models/operations/replacecompanyrequest.md index 1de44d982..2b90faf30 100644 --- a/sync-for-payables/docs/models/operations/replacecompanyrequest.md +++ b/sync-for-payables/docs/models/operations/replacecompanyrequest.md @@ -1,9 +1,9 @@ -# ReplaceCompanyRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +# ReplaceCompanyRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | | `company_request_body` | [Optional[shared.CompanyRequestBody]](../../models/shared/companyrequestbody.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/sync-for-payables/docs/models/operations/unlinkconnectionrequest.md b/sync-for-payables/docs/models/operations/unlinkconnectionrequest.md index 79d8b2072..66136f30f 100644 --- a/sync-for-payables/docs/models/operations/unlinkconnectionrequest.md +++ b/sync-for-payables/docs/models/operations/unlinkconnectionrequest.md @@ -1,10 +1,10 @@ -# UnlinkConnectionRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | -| `request_body` | [Optional[operations.UnlinkConnectionUpdateConnection]](../../models/operations/unlinkconnectionupdateconnection.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file +# UnlinkConnectionRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | +| `request_body` | [Optional[shared.UpdateConnection]](../../models/shared/updateconnection.md) | :heavy_minus_sign: | N/A | | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | \ No newline at end of file diff --git a/sync-for-payables/docs/models/operations/unlinkconnectionupdateconnection.md b/sync-for-payables/docs/models/operations/unlinkconnectionupdateconnection.md index 5a5f2911b..476521561 100644 --- a/sync-for-payables/docs/models/operations/unlinkconnectionupdateconnection.md +++ b/sync-for-payables/docs/models/operations/unlinkconnectionupdateconnection.md @@ -1,8 +1,9 @@ -# UnlinkConnectionUpdateConnection - - -## Fields - -| Field | Type | Required | Description | -| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | +# UnlinkConnectionUpdateConnection + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | +| `additional_properties` | Dict[str, *Any*] | :heavy_check_mark: | N/A | | `status` | [Optional[shared.DataConnectionStatus]](../../models/shared/dataconnectionstatus.md) | :heavy_minus_sign: | The current authorization status of the data connection. | \ No newline at end of file diff --git a/sync-for-payables/docs/models/operations/updatebillrequest.md b/sync-for-payables/docs/models/operations/updatebillrequest.md index 749e460bd..7b31c2c67 100644 --- a/sync-for-payables/docs/models/operations/updatebillrequest.md +++ b/sync-for-payables/docs/models/operations/updatebillrequest.md @@ -1,12 +1,12 @@ -# UpdateBillRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | -| `bill_id` | *str* | :heavy_check_mark: | Unique identifier for a bill. | **Example 1:** 13d946f0-c5d5-42bc-b092-97ece17923ab
**Example 2:** 9wg4lep4ush5cxs79pl8sozmsndbaukll3ind4g7buqbm1h2
**Example 3:** 7110701885
**Example 4:** EILBDVJVNUAGVKRQ | -| `idempotency_key` | *Optional[str]* | :heavy_minus_sign: | A unique identifier to ensure idempotent behaviour for subsequent requests. | | -| `bill_prototype` | [Optional[shared.BillPrototype]](../../models/shared/billprototype.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file +# UpdateBillRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `bill_id` | *str* | :heavy_check_mark: | Unique identifier for a bill. | **Example 1:** 13d946f0-c5d5-42bc-b092-97ece17923ab
**Example 2:** 9wg4lep4ush5cxs79pl8sozmsndbaukll3ind4g7buqbm1h2
**Example 3:** 7110701885
**Example 4:** EILBDVJVNUAGVKRQ | +| `bill_prototype` | [Optional[shared.BillPrototype]](../../models/shared/billprototype.md) | :heavy_minus_sign: | N/A | | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | +| `idempotency_key` | *Optional[str]* | :heavy_minus_sign: | A unique identifier to ensure idempotent behaviour for subsequent requests. | | \ No newline at end of file diff --git a/sync-for-payables/docs/models/operations/updatecompanyrequest.md b/sync-for-payables/docs/models/operations/updatecompanyrequest.md index d2d812198..9718e2ff6 100644 --- a/sync-for-payables/docs/models/operations/updatecompanyrequest.md +++ b/sync-for-payables/docs/models/operations/updatecompanyrequest.md @@ -1,9 +1,9 @@ -# UpdateCompanyRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +# UpdateCompanyRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | | `company_update_request` | [Optional[shared.CompanyUpdateRequest]](../../models/shared/companyupdaterequest.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/sync-for-payables/docs/models/operations/updatesupplierrequest.md b/sync-for-payables/docs/models/operations/updatesupplierrequest.md index 9a051fa2f..d0871cf41 100644 --- a/sync-for-payables/docs/models/operations/updatesupplierrequest.md +++ b/sync-for-payables/docs/models/operations/updatesupplierrequest.md @@ -1,11 +1,11 @@ -# UpdateSupplierRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | -| `supplier_id` | *str* | :heavy_check_mark: | Unique identifier for a supplier. | **Example 1:** 13d946f0-c5d5-42bc-b092-97ece17923ab
**Example 2:** 9wg4lep4ush5cxs79pl8sozmsndbaukll3ind4g7buqbm1h2
**Example 3:** 7110701885
**Example 4:** EILBDVJVNUAGVKRQ | +# UpdateSupplierRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | +| `supplier_id` | *str* | :heavy_check_mark: | Unique identifier for a supplier. | **Example 1:** 13d946f0-c5d5-42bc-b092-97ece17923ab
**Example 2:** 9wg4lep4ush5cxs79pl8sozmsndbaukll3ind4g7buqbm1h2
**Example 3:** 7110701885
**Example 4:** EILBDVJVNUAGVKRQ | | `supplier_prototype` | [Optional[shared.SupplierPrototype]](../../models/shared/supplierprototype.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/sync-for-payables/docs/models/operations/uploadbillattachmentrequest.md b/sync-for-payables/docs/models/operations/uploadbillattachmentrequest.md index 7b2ccd399..6a76ecb7f 100644 --- a/sync-for-payables/docs/models/operations/uploadbillattachmentrequest.md +++ b/sync-for-payables/docs/models/operations/uploadbillattachmentrequest.md @@ -1,11 +1,11 @@ -# UploadBillAttachmentRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | -| `bill_id` | *str* | :heavy_check_mark: | Unique identifier for a bill. | **Example 1:** 13d946f0-c5d5-42bc-b092-97ece17923ab
**Example 2:** 9wg4lep4ush5cxs79pl8sozmsndbaukll3ind4g7buqbm1h2
**Example 3:** 7110701885
**Example 4:** EILBDVJVNUAGVKRQ | -| `attachment_upload` | [Optional[shared.AttachmentUpload]](../../models/shared/attachmentupload.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file +# UploadBillAttachmentRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `attachment_upload` | [Optional[shared.AttachmentUpload]](../../models/shared/attachmentupload.md) | :heavy_minus_sign: | N/A | | +| `bill_id` | *str* | :heavy_check_mark: | Unique identifier for a bill. | **Example 1:** 13d946f0-c5d5-42bc-b092-97ece17923ab
**Example 2:** 9wg4lep4ush5cxs79pl8sozmsndbaukll3ind4g7buqbm1h2
**Example 3:** 7110701885
**Example 4:** EILBDVJVNUAGVKRQ | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `connection_id` | *str* | :heavy_check_mark: | Unique identifier for a connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/accountmappingoption.md b/sync-for-payables/docs/models/shared/accountmappingoption.md index 1c1d60088..fdf71d8a1 100644 --- a/sync-for-payables/docs/models/shared/accountmappingoption.md +++ b/sync-for-payables/docs/models/shared/accountmappingoption.md @@ -1,14 +1,14 @@ -# AccountMappingOption - - -## Fields - -| Field | Type | Required | Description | Example | -| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `id` | *Optional[str]* | :heavy_minus_sign: | Identifier for the account, unique for the company. | 1b6266d1-1e44-46c5-8eb5-a8f98e03124e | -| `nominal_code` | *OptionalNullable[str]* | :heavy_minus_sign: | Reference given to each nominal account for a business. It ensures money is allocated to the correct account. This code isn't a unique identifier in the Codat system. | 610 | -| `name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the account. | Accounts Payable | -| `type` | *OptionalNullable[str]* | :heavy_minus_sign: | Type of account. | Liability | -| `currency` | *Optional[str]* | :heavy_minus_sign: | The currency data type in Codat is the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code, e.g. _GBP_.

## Unknown currencies

In line with the ISO 4217 specification, the code _XXX_ is used when the data source does not return a currency for a transaction.

There are only a very small number of edge cases where this currency code is returned by the Codat system. | **Example 1:** GBP
**Example 2:** USD
**Example 3:** EUR | -| `status` | [Optional[shared.AccountStatus]](../../models/shared/accountstatus.md) | :heavy_minus_sign: | The current status of the account. | Active | -| `source_modified_date` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | \ No newline at end of file +# AccountMappingOption + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `currency` | *Optional[str]* | :heavy_minus_sign: | The currency data type in Codat is the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code, e.g. _GBP_. ## Unknown currencies In line with the ISO 4217 specification, the code _XXX_ is used when the data source does not return a currency for a transaction. There are only a very small number of edge cases where this currency code is returned by the Codat system. | +| `id` | *Optional[str]* | :heavy_minus_sign: | Identifier for the account, unique for the company. | +| `name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the account. | +| `nominal_code` | *OptionalNullable[str]* | :heavy_minus_sign: | Reference given to each nominal account for a business. It ensures money is allocated to the correct account. This code isn't a unique identifier in the Codat system. | +| `source_modified_date` | *Optional[str]* | :heavy_minus_sign: | The date when a record was last modified in the accounting software, usually by the business or a business process. For example, when payments are made against an invoice. It is not populated ([read more](https://docs.codat.io/using-the-api/modified-dates#source-modified-date)) when: - Pulling attachments - The accounting software does not provide modification dates for a data type - A record has been deleted from the source platform and Codat doesn't have a record of when the deletion occurred - A record has been voided. For certain platforms that soft delete records, `isDeleted` metadata is used to identify void records In Codat's data model, dates and times are represented using the ISO 8601 standard. | +| `status` | [Optional[shared.AccountStatus]](../../models/shared/accountstatus.md) | :heavy_minus_sign: | N/A | +| `type` | *OptionalNullable[str]* | :heavy_minus_sign: | Type of account. | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/accountstatus.md b/sync-for-payables/docs/models/shared/accountstatus.md index 25d7260e0..cfa19e311 100644 --- a/sync-for-payables/docs/models/shared/accountstatus.md +++ b/sync-for-payables/docs/models/shared/accountstatus.md @@ -1,19 +1,17 @@ -# AccountStatus - -The current status of the account. - -## Example Usage - -```python -from codat_sync_for_payables.models.shared import AccountStatus - -value = AccountStatus.ACTIVE -``` - - -## Values - -| Name | Value | -| ---------- | ---------- | -| `ACTIVE` | Active | +# AccountStatus + +## Example Usage + +```python +from codat_sync_for_payables.models.shared import AccountStatus + +value = AccountStatus.ACTIVE +``` + + +## Values + +| Name | Value | +| ---------- | ---------- | +| `ACTIVE` | Active | | `ARCHIVED` | Archived | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/address.md b/sync-for-payables/docs/models/shared/address.md index 331efc47c..d22146172 100644 --- a/sync-for-payables/docs/models/shared/address.md +++ b/sync-for-payables/docs/models/shared/address.md @@ -1,14 +1,14 @@ -# Address - - -## Fields - -| Field | Type | Required | Description | -| ---------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -| `type` | [Optional[shared.AddressType]](../../models/shared/addresstype.md) | :heavy_minus_sign: | The type of the address | -| `line1` | *OptionalNullable[str]* | :heavy_minus_sign: | Line 1 of the customer address. | -| `line2` | *OptionalNullable[str]* | :heavy_minus_sign: | Line 2 of the customer address. | -| `city` | *OptionalNullable[str]* | :heavy_minus_sign: | City of the customer address. | -| `region` | *OptionalNullable[str]* | :heavy_minus_sign: | Region of the customer address. | -| `country` | *OptionalNullable[str]* | :heavy_minus_sign: | Country of the address. We recommend using the 2-digit ISO 3166 country code (e.g. `GB`, `US`, `FR`) as this is accepted by all supported platforms. | -| `postal_code` | *OptionalNullable[str]* | :heavy_minus_sign: | Postal code or zip code. | \ No newline at end of file +# Address + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | +| `city` | *OptionalNullable[str]* | :heavy_minus_sign: | City of the customer address. | +| `country` | *OptionalNullable[str]* | :heavy_minus_sign: | Country of the address. We recommend using the 2-digit ISO 3166 country code (e.g. `GB`, `US`, `FR`) as this is accepted by all supported platforms. | +| `line1` | *OptionalNullable[str]* | :heavy_minus_sign: | Line 1 of the customer address. | +| `line2` | *OptionalNullable[str]* | :heavy_minus_sign: | Line 2 of the customer address. | +| `postal_code` | *OptionalNullable[str]* | :heavy_minus_sign: | Postal code or zip code. | +| `region` | *OptionalNullable[str]* | :heavy_minus_sign: | Region of the customer address. | +| `type` | [Optional[shared.AddressType]](../../models/shared/addresstype.md) | :heavy_minus_sign: | The type of the address | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/addresstype.md b/sync-for-payables/docs/models/shared/addresstype.md index 496df553c..4c4270572 100644 --- a/sync-for-payables/docs/models/shared/addresstype.md +++ b/sync-for-payables/docs/models/shared/addresstype.md @@ -1,20 +1,18 @@ -# AddressType - -The type of the address - -## Example Usage - -```python -from codat_sync_for_payables.models.shared import AddressType - -value = AddressType.UNKNOWN -``` - - -## Values - -| Name | Value | -| ---------- | ---------- | -| `UNKNOWN` | Unknown | -| `BILLING` | Billing | +# AddressType + +## Example Usage + +```python +from codat_sync_for_payables.models.shared import AddressType + +value = AddressType.UNKNOWN +``` + + +## Values + +| Name | Value | +| ---------- | ---------- | +| `UNKNOWN` | Unknown | +| `BILLING` | Billing | | `DELIVERY` | Delivery | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/attachment.md b/sync-for-payables/docs/models/shared/attachment.md index 129d601b3..83370f819 100644 --- a/sync-for-payables/docs/models/shared/attachment.md +++ b/sync-for-payables/docs/models/shared/attachment.md @@ -1,31 +1,31 @@ -# Attachment - - The Codat API supports pulling and pushing of file attachments for invoices, bills, direct costs, and direct incomes. - - > **Retrieving attachments** - > - > If a company is authorized, you can query the Codat API to read, download, and upload attachments without requiring a fresh sync of data. - - Unlike other data types, Codat doesn't support [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings) for attachments. - - Note that different integrations have different requirements for file size and extension of attachments. - - | Integration | File size | File extension | - |-------------------|-----------|--------------------------------------------------------------------------------------------------------------------------------------------------------------| - | Xero | 4 MB | 7Z, BMP, CSV, DOC, DOCX, EML, GIF, JPEG, JPG, KEYNOTE, MSG, NUMBERS, ODF, ODS, ODT, PAGES, PDF, PNG, PPT, PPTX, RAR, RTF, TIF, TIFF, TXT, XLS, XLSX, ZIP | - | QuickBooks Online | 100 MB | AI, CSV, DOC, DOCX, EPS, GIF, JPEG, JPG, ODS, PAGES, PDF, PNG, RTF, TIF, TXT, XLS, XLSX, XML | - | NetSuite | 100 MB | BMP, CSV, XLS, XLSX, JSON, PDF, PJPG, PJPEG, PNG, TXT, SVG, TIF, TIFF, DOC, DOCX, ZIP | - | Dynamics 365 Business Central | 350 MB | Dynamics do not explicitly outline which file types are supported but they do state here that "You can attach any type of file, such as text, image, or video files". | - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `id` | *Optional[str]* | :heavy_minus_sign: | Identifier for the attachment, unique for the company in the accounting software. | | -| `name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the attachment file. | | -| `content_type` | *OptionalNullable[str]* | :heavy_minus_sign: | File type of the attachment. This is represented by appending the file type to the [IETF standard file naming requirements](https://tools.ietf.org/html/rfc6838). For example, for a jpeg file the output is **image/jpeg**.

Supported file types vary per platform. | | -| `date_created` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `file_size` | *OptionalNullable[int]* | :heavy_minus_sign: | File size in bytes. For example, if this reads **46153**, then the file size is 46kb. | | -| `include_when_sent` | *Optional[bool]* | :heavy_minus_sign: | If `true`, then the attachment is included with the associated invoice, bill or direct costs when it is printed, emailed, or sent to a customer, if the underlying accounting software allows this. | | +# Attachment + + The Codat API supports pulling and pushing of file attachments for invoices, bills, direct costs, and direct incomes. + + > **Retrieving attachments** + > + > If a company is authorized, you can query the Codat API to read, download, and upload attachments without requiring a fresh sync of data. + + Unlike other data types, Codat doesn't support [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings) for attachments. + + Note that different integrations have different requirements for file size and extension of attachments. + + | Integration | File size | File extension | + |-------------------|-----------|--------------------------------------------------------------------------------------------------------------------------------------------------------------| + | Xero | 4 MB | 7Z, BMP, CSV, DOC, DOCX, EML, GIF, JPEG, JPG, KEYNOTE, MSG, NUMBERS, ODF, ODS, ODT, PAGES, PDF, PNG, PPT, PPTX, RAR, RTF, TIF, TIFF, TXT, XLS, XLSX, ZIP | + | QuickBooks Online | 100 MB | AI, CSV, DOC, DOCX, EPS, GIF, JPEG, JPG, ODS, PAGES, PDF, PNG, RTF, TIF, TXT, XLS, XLSX, XML | + | NetSuite | 100 MB | BMP, CSV, XLS, XLSX, JSON, PDF, PJPG, PJPEG, PNG, TXT, SVG, TIF, TIFF, DOC, DOCX, ZIP | + | Dynamics 365 Business Central | 350 MB | Dynamics do not explicitly outline which file types are supported but they do state here that "You can attach any type of file, such as text, image, or video files". | + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `content_type` | *OptionalNullable[str]* | :heavy_minus_sign: | File type of the attachment. This is represented by appending the file type to the [IETF standard file naming requirements](https://tools.ietf.org/html/rfc6838). For example, for a jpeg file the output is **image/jpeg**.

Supported file types vary per platform. | | +| `date_created` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `file_size` | *OptionalNullable[int]* | :heavy_minus_sign: | File size in bytes. For example, if this reads **46153**, then the file size is 46kb. | | +| `id` | *Optional[str]* | :heavy_minus_sign: | Identifier for the attachment, unique for the company in the accounting software. | | +| `include_when_sent` | *Optional[bool]* | :heavy_minus_sign: | If `true`, then the attachment is included with the associated invoice, bill or direct costs when it is printed, emailed, or sent to a customer, if the underlying accounting software allows this. | | +| `name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the attachment file. | | | `source_modified_date` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/attachmentupload.md b/sync-for-payables/docs/models/shared/attachmentupload.md index 02d7ac41a..7581412bd 100644 --- a/sync-for-payables/docs/models/shared/attachmentupload.md +++ b/sync-for-payables/docs/models/shared/attachmentupload.md @@ -1,8 +1,8 @@ -# AttachmentUpload - - -## Fields - -| Field | Type | Required | Description | -| ---------------------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------- | +# AttachmentUpload + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------- | | `file` | [shared.CodatFile](../../models/shared/codatfile.md) | :heavy_check_mark: | The file to be uploaded as an attachment. | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/bankaccount.md b/sync-for-payables/docs/models/shared/bankaccount.md index 25fff9fdc..55265abc2 100644 --- a/sync-for-payables/docs/models/shared/bankaccount.md +++ b/sync-for-payables/docs/models/shared/bankaccount.md @@ -1,16 +1,16 @@ -# BankAccount - - -## Fields - -| Field | Type | Required | Description | Example | -| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `id` | *Optional[str]* | :heavy_minus_sign: | Identifier for the bank account, unique for the company in the accounting software. | | -| `nominal_code` | *OptionalNullable[str]* | :heavy_minus_sign: | Code used to identify each nominal account for a business. | | -| `name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the bank account in the accounting software. | | -| `account_type` | [Optional[shared.BankAccountType]](../../models/shared/bankaccounttype.md) | :heavy_minus_sign: | The type of transactions and balances on the account.
For Credit accounts, positive balances are liabilities, and positive transactions **reduce** liabilities.
For Debit accounts, positive balances are assets, and positive transactions **increase** assets. | | -| `account_number` | *OptionalNullable[str]* | :heavy_minus_sign: | Account number for the bank account.

Xero integrations
Only a UK account number shows for bank accounts with GBP currency and a combined total of sort code and account number that equals 14 digits, For non-GBP accounts, the full bank account number is populated. | | -| `sort_code` | *OptionalNullable[str]* | :heavy_minus_sign: | Sort code for the bank account. This is relevant to UK bank accounts.

Xero integrations
The sort code is only displayed when the currency = GBP and the sort code and account number sum to 14 digits. For non-GBP accounts, this field is not populated. | | -| `currency` | *Optional[str]* | :heavy_minus_sign: | The currency data type in Codat is the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code, e.g. _GBP_.

## Unknown currencies

In line with the ISO 4217 specification, the code _XXX_ is used when the data source does not return a currency for a transaction.

There are only a very small number of edge cases where this currency code is returned by the Codat system. | **Example 1:** GBP
**Example 2:** USD
**Example 3:** EUR | -| `status` | [Optional[shared.BankAccountStatus]](../../models/shared/bankaccountstatus.md) | :heavy_minus_sign: | The current status of the bank account. | Active | -| `source_modified_date` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | \ No newline at end of file +# BankAccount + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `account_number` | *OptionalNullable[str]* | :heavy_minus_sign: | Account number for the bank account.

Xero integrations
Only a UK account number shows for bank accounts with GBP currency and a combined total of sort code and account number that equals 14 digits, For non-GBP accounts, the full bank account number is populated. | | +| `account_type` | [Optional[shared.BankAccountType]](../../models/shared/bankaccounttype.md) | :heavy_minus_sign: | The type of transactions and balances on the account.
For Credit accounts, positive balances are liabilities, and positive transactions **reduce** liabilities.
For Debit accounts, positive balances are assets, and positive transactions **increase** assets. | | +| `currency` | *Optional[str]* | :heavy_minus_sign: | The currency data type in Codat is the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code, e.g. _GBP_.

## Unknown currencies

In line with the ISO 4217 specification, the code _XXX_ is used when the data source does not return a currency for a transaction.

There are only a very small number of edge cases where this currency code is returned by the Codat system. | **Example 1:** GBP
**Example 2:** USD
**Example 3:** EUR | +| `id` | *Optional[str]* | :heavy_minus_sign: | Identifier for the bank account, unique for the company in the accounting software. | | +| `name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the bank account in the accounting software. | | +| `nominal_code` | *OptionalNullable[str]* | :heavy_minus_sign: | Code used to identify each nominal account for a business. | | +| `sort_code` | *OptionalNullable[str]* | :heavy_minus_sign: | Sort code for the bank account. This is relevant to UK bank accounts.

Xero integrations
The sort code is only displayed when the currency = GBP and the sort code and account number sum to 14 digits. For non-GBP accounts, this field is not populated. | | +| `source_modified_date` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `status` | [Optional[shared.BankAccountStatus]](../../models/shared/bankaccountstatus.md) | :heavy_minus_sign: | The current status of the bank account. | | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/bankaccountmappingoption.md b/sync-for-payables/docs/models/shared/bankaccountmappingoption.md index e4a4d459b..96e0b1caa 100644 --- a/sync-for-payables/docs/models/shared/bankaccountmappingoption.md +++ b/sync-for-payables/docs/models/shared/bankaccountmappingoption.md @@ -1,16 +1,16 @@ -# BankAccountMappingOption - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `id` | *Optional[str]* | :heavy_minus_sign: | Identifier for the account, unique for the company in the accounting software. | 3d5a8e00-d108-4045-8823-7f342676cffa | -| `name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the bank account in the accounting software. | Bank of Dave current account | -| `account_number` | *OptionalNullable[str]* | :heavy_minus_sign: | Account number for the bank account.

Xero integrations
Only a UK account number shows for bank accounts with GBP currency and a combined total of sort code and account number that equals 14 digits, For non-GBP accounts, the full bank account number is populated. | | -| `nominal_code` | *OptionalNullable[str]* | :heavy_minus_sign: | Code used to identify each nominal account for a business. | | -| `sort_code` | *OptionalNullable[str]* | :heavy_minus_sign: | Sort code for the bank account.

Xero integrations
The sort code is only displayed when the currency = GBP and the sort code and account number sum to 14 digits. For non-GBP accounts, this field is not populated. | | -| `currency` | *OptionalNullable[str]* | :heavy_minus_sign: | The bank account's base currency. | | -| `status` | [Optional[shared.BankAccountStatus]](../../models/shared/bankaccountstatus.md) | :heavy_minus_sign: | The current status of the bank account. | Active | -| `account_type` | [Optional[shared.BankAccountType]](../../models/shared/bankaccounttype.md) | :heavy_minus_sign: | The type of transactions and balances on the account.
For Credit accounts, positive balances are liabilities, and positive transactions **reduce** liabilities.
For Debit accounts, positive balances are assets, and positive transactions **increase** assets. | | -| `source_modified_date` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | \ No newline at end of file +# BankAccountMappingOption + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `account_number` | *OptionalNullable[str]* | :heavy_minus_sign: | Account number for the bank account. Xero integrations Only a UK account number shows for bank accounts with GBP currency and a combined total of sort code and account number that equals 14 digits, For non-GBP accounts, the full bank account number is populated. | +| `account_type` | [Optional[shared.BankAccountType]](../../models/shared/bankaccounttype.md) | :heavy_minus_sign: | N/A | +| `currency` | *OptionalNullable[str]* | :heavy_minus_sign: | The bank account's base currency. | +| `id` | *Optional[str]* | :heavy_minus_sign: | Identifier for the account, unique for the company in the accounting software. | +| `name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the bank account in the accounting software. | +| `nominal_code` | *OptionalNullable[str]* | :heavy_minus_sign: | Code used to identify each nominal account for a business. | +| `sort_code` | *OptionalNullable[str]* | :heavy_minus_sign: | Sort code for the bank account. Xero integrations The sort code is only displayed when the currency = GBP and the sort code and account number sum to 14 digits. For non-GBP accounts, this field is not populated. | +| `source_modified_date` | *Optional[str]* | :heavy_minus_sign: | The date when a record was last modified in the accounting software, usually by the business or a business process. For example, when payments are made against an invoice. It is not populated ([read more](https://docs.codat.io/using-the-api/modified-dates#source-modified-date)) when: - Pulling attachments - The accounting software does not provide modification dates for a data type - A record has been deleted from the source platform and Codat doesn't have a record of when the deletion occurred - A record has been voided. For certain platforms that soft delete records, `isDeleted` metadata is used to identify void records In Codat's data model, dates and times are represented using the ISO 8601 standard. | +| `status` | [Optional[shared.BankAccountStatus]](../../models/shared/bankaccountstatus.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/bankaccountprototype.md b/sync-for-payables/docs/models/shared/bankaccountprototype.md index a16edf50b..026b5a67e 100644 --- a/sync-for-payables/docs/models/shared/bankaccountprototype.md +++ b/sync-for-payables/docs/models/shared/bankaccountprototype.md @@ -1,13 +1,13 @@ -# BankAccountPrototype - - -## Fields - -| Field | Type | Required | Description | Example | -| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `nominal_code` | *OptionalNullable[str]* | :heavy_minus_sign: | Code used to identify each nominal account for a business. | | -| `name` | *Nullable[str]* | :heavy_check_mark: | Name of the bank account in the accounting software. | | -| `account_type` | [shared.BankAccountType](../../models/shared/bankaccounttype.md) | :heavy_check_mark: | The type of transactions and balances on the account.
For Credit accounts, positive balances are liabilities, and positive transactions **reduce** liabilities.
For Debit accounts, positive balances are assets, and positive transactions **increase** assets. | | -| `account_number` | *Nullable[str]* | :heavy_check_mark: | Account number for the bank account.

Xero integrations
Only a UK account number shows for bank accounts with GBP currency and a combined total of sort code and account number that equals 14 digits, For non-GBP accounts, the full bank account number is populated. | | -| `sort_code` | *OptionalNullable[str]* | :heavy_minus_sign: | Sort code for the bank account. This is relevant to UK bank accounts.

Xero integrations
The sort code is only displayed when the currency = GBP and the sort code and account number sum to 14 digits. For non-GBP accounts, this field is not populated. | | -| `currency` | *str* | :heavy_check_mark: | The currency data type in Codat is the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code, e.g. _GBP_.

## Unknown currencies

In line with the ISO 4217 specification, the code _XXX_ is used when the data source does not return a currency for a transaction.

There are only a very small number of edge cases where this currency code is returned by the Codat system. | **Example 1:** GBP
**Example 2:** USD
**Example 3:** EUR | \ No newline at end of file +# BankAccountPrototype + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `account_number` | *str* | :heavy_check_mark: | Account number for the bank account.

Xero integrations
Only a UK account number shows for bank accounts with GBP currency and a combined total of sort code and account number that equals 14 digits, For non-GBP accounts, the full bank account number is populated. | | +| `account_type` | [shared.BankAccountType](../../models/shared/bankaccounttype.md) | :heavy_check_mark: | The type of transactions and balances on the account.
For Credit accounts, positive balances are liabilities, and positive transactions **reduce** liabilities.
For Debit accounts, positive balances are assets, and positive transactions **increase** assets. | | +| `currency` | *str* | :heavy_check_mark: | The currency data type in Codat is the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code, e.g. _GBP_.

## Unknown currencies

In line with the ISO 4217 specification, the code _XXX_ is used when the data source does not return a currency for a transaction.

There are only a very small number of edge cases where this currency code is returned by the Codat system. | **Example 1:** GBP
**Example 2:** USD
**Example 3:** EUR | +| `name` | *str* | :heavy_check_mark: | Name of the bank account in the accounting software. | | +| `nominal_code` | *OptionalNullable[str]* | :heavy_minus_sign: | Code used to identify each nominal account for a business. | | +| `sort_code` | *OptionalNullable[str]* | :heavy_minus_sign: | Sort code for the bank account. This is relevant to UK bank accounts.

Xero integrations
The sort code is only displayed when the currency = GBP and the sort code and account number sum to 14 digits. For non-GBP accounts, this field is not populated. | | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/bankaccountstatus.md b/sync-for-payables/docs/models/shared/bankaccountstatus.md index 5917acb4c..db8818a59 100644 --- a/sync-for-payables/docs/models/shared/bankaccountstatus.md +++ b/sync-for-payables/docs/models/shared/bankaccountstatus.md @@ -1,19 +1,17 @@ -# BankAccountStatus - -The current status of the bank account. - -## Example Usage - -```python -from codat_sync_for_payables.models.shared import BankAccountStatus - -value = BankAccountStatus.ACTIVE -``` - - -## Values - -| Name | Value | -| ---------- | ---------- | -| `ACTIVE` | Active | +# BankAccountStatus + +## Example Usage + +```python +from codat_sync_for_payables.models.shared import BankAccountStatus + +value = BankAccountStatus.ACTIVE +``` + + +## Values + +| Name | Value | +| ---------- | ---------- | +| `ACTIVE` | Active | | `ARCHIVED` | Archived | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/bankaccounttype.md b/sync-for-payables/docs/models/shared/bankaccounttype.md index 7186a1bf5..63df17798 100644 --- a/sync-for-payables/docs/models/shared/bankaccounttype.md +++ b/sync-for-payables/docs/models/shared/bankaccounttype.md @@ -1,22 +1,22 @@ -# BankAccountType - -The type of transactions and balances on the account. -For Credit accounts, positive balances are liabilities, and positive transactions **reduce** liabilities. -For Debit accounts, positive balances are assets, and positive transactions **increase** assets. - -## Example Usage - -```python -from codat_sync_for_payables.models.shared import BankAccountType - -value = BankAccountType.UNKNOWN -``` - - -## Values - -| Name | Value | -| --------- | --------- | -| `UNKNOWN` | Unknown | -| `CREDIT` | Credit | +# BankAccountType + +The type of transactions and balances on the account. +For Credit accounts, positive balances are liabilities, and positive transactions **reduce** liabilities. +For Debit accounts, positive balances are assets, and positive transactions **increase** assets. + +## Example Usage + +```python +from codat_sync_for_payables.models.shared import BankAccountType + +value = BankAccountType.UNKNOWN +``` + + +## Values + +| Name | Value | +| --------- | --------- | +| `UNKNOWN` | Unknown | +| `CREDIT` | Credit | | `DEBIT` | Debit | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/bill.md b/sync-for-payables/docs/models/shared/bill.md index 9989e1a3f..4a166f797 100644 --- a/sync-for-payables/docs/models/shared/bill.md +++ b/sync-for-payables/docs/models/shared/bill.md @@ -1,21 +1,21 @@ -# Bill - -Bills are invoices that represent the SMB's financial obligations to their supplier for a purchase of goods or services. - - -## Fields - -| Field | Type | Required | Description | Example | -| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `id` | *Optional[str]* | :heavy_minus_sign: | Identifier for the bill, unique for the company in the accounting software. | | -| `reference` | *OptionalNullable[str]* | :heavy_minus_sign: | User-friendly reference for the bill. | | -| `supplier_ref` | [shared.SupplierRef](../../models/shared/supplierref.md) | :heavy_check_mark: | Reference to the supplier the record relates to. | | -| `issue_date` | *str* | :heavy_check_mark: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `due_date` | *str* | :heavy_check_mark: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `currency` | *str* | :heavy_check_mark: | The currency data type in Codat is the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code, e.g. _GBP_.

## Unknown currencies

In line with the ISO 4217 specification, the code _XXX_ is used when the data source does not return a currency for a transaction.

There are only a very small number of edge cases where this currency code is returned by the Codat system. | **Example 1:** GBP
**Example 2:** USD
**Example 3:** EUR | -| `currency_rate` | *OptionalNullable[Decimal]* | :heavy_minus_sign: | Rate to convert the total amount of the payment into the base currency for the company at the time of the payment.

Currency rates in Codat are implemented as the multiple of foreign currency units to each base currency unit.

It is not possible to perform the currency conversion with two or more non-base currencies participating in the transaction. For example, if a company's base currency is USD, and it has a bill issued in EUR, then the bill payment must happen in USD or EUR.

Where the currency rate is provided by the underlying accounting software, it will be available from Codat with the same precision (up to a maximum of 9 decimal places).

For accounting software which do not provide an explicit currency rate, it is calculated as `baseCurrency / foreignCurrency` and will be returned to 9 decimal places.

## Examples with base currency of GBP

\| Foreign Currency \| Foreign Amount \| Currency Rate \| Base Currency Amount (GBP) \|
\| :--------------- \| :------------- \| :------------ \| :------------------------- \|
\| **USD** \| $20 \| 0.781 \| £15.62 \|
\| **EUR** \| €20 \| 0.885 \| £17.70 \|
\| **RUB** \| ₽20 \| 0.011 \| £0.22 \|

## Examples with base currency of USD

\| Foreign Currency \| Foreign Amount \| Currency Rate \| Base Currency Amount (USD) \|
\| :--------------- \| :------------- \| :------------ \| :------------------------- \|
\| **GBP** \| £20 \| 1.277 \| $25.54 \|
\| **EUR** \| €20 \| 1.134 \| $22.68 \|
\| **RUB** \| ₽20 \| 0.015 \| $0.30 \|


### Integration-specific details

\| Integration \| Scenario \| System behavior \|
\|-------------------\|-------------------------------------------------\|----------------------------------------------------------------------------------------------------------------------------------------------------------------------\|
\| QuickBooks Online \| Transaction currency differs from base currency \| If currency rate value is left `null`, a rate of 1 will be used by QBO by default. To override this, specify a currencyRate in the request body. \| | | -| `line_items` | List[[shared.BillLineItem](../../models/shared/billlineitem.md)] | :heavy_minus_sign: | Array of Bill line items. | | -| `status` | [shared.BillStatus](../../models/shared/billstatus.md) | :heavy_check_mark: | Current state of the bill. If creating a bill the status must be `Open`. | Open | -| `total_amount` | *Optional[Decimal]* | :heavy_minus_sign: | Amount of the bill, including tax. | | -| `amount_due` | *OptionalNullable[Decimal]* | :heavy_minus_sign: | Amount outstanding on the bill. | | -| `source_modified_date` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | \ No newline at end of file +# Bill + +Bills are invoices that represent the SMB's financial obligations to their supplier for a purchase of goods or services. + + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `amount_due` | *OptionalNullable[Decimal]* | :heavy_minus_sign: | Amount outstanding on the bill. | | +| `currency` | *str* | :heavy_check_mark: | The currency data type in Codat is the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code, e.g. _GBP_.

## Unknown currencies

In line with the ISO 4217 specification, the code _XXX_ is used when the data source does not return a currency for a transaction.

There are only a very small number of edge cases where this currency code is returned by the Codat system. | **Example 1:** GBP
**Example 2:** USD
**Example 3:** EUR | +| `currency_rate` | *OptionalNullable[Decimal]* | :heavy_minus_sign: | Rate to convert the total amount of the payment into the base currency for the company at the time of the payment.

Currency rates in Codat are implemented as the multiple of foreign currency units to each base currency unit.

It is not possible to perform the currency conversion with two or more non-base currencies participating in the transaction. For example, if a company's base currency is USD, and it has a bill issued in EUR, then the bill payment must happen in USD or EUR.

Where the currency rate is provided by the underlying accounting software, it will be available from Codat with the same precision (up to a maximum of 9 decimal places).

For accounting software which do not provide an explicit currency rate, it is calculated as `baseCurrency / foreignCurrency` and will be returned to 9 decimal places.

## Examples with base currency of GBP

\| Foreign Currency \| Foreign Amount \| Currency Rate \| Base Currency Amount (GBP) \|
\| :--------------- \| :------------- \| :------------ \| :------------------------- \|
\| **USD** \| $20 \| 0.781 \| £15.62 \|
\| **EUR** \| €20 \| 0.885 \| £17.70 \|
\| **RUB** \| ₽20 \| 0.011 \| £0.22 \|

## Examples with base currency of USD

\| Foreign Currency \| Foreign Amount \| Currency Rate \| Base Currency Amount (USD) \|
\| :--------------- \| :------------- \| :------------ \| :------------------------- \|
\| **GBP** \| £20 \| 1.277 \| $25.54 \|
\| **EUR** \| €20 \| 1.134 \| $22.68 \|
\| **RUB** \| ₽20 \| 0.015 \| $0.30 \|


### Integration-specific details

\| Integration \| Scenario \| System behavior \|
\|-------------------\|-------------------------------------------------\|----------------------------------------------------------------------------------------------------------------------------------------------------------------------\|
\| QuickBooks Online \| Transaction currency differs from base currency \| If currency rate value is left `null`, a rate of 1 will be used by QBO by default. To override this, specify a currencyRate in the request body. \| | | +| `due_date` | *str* | :heavy_check_mark: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `id` | *Optional[str]* | :heavy_minus_sign: | Identifier for the bill, unique for the company in the accounting software. | | +| `issue_date` | *str* | :heavy_check_mark: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `line_items` | List[[shared.BillLineItem](../../models/shared/billlineitem.md)] | :heavy_minus_sign: | Array of Bill line items. | | +| `reference` | *OptionalNullable[str]* | :heavy_minus_sign: | User-friendly reference for the bill. | | +| `source_modified_date` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `status` | [shared.BillStatus](../../models/shared/billstatus.md) | :heavy_check_mark: | Current state of the bill. If creating a bill the status must be `Open`. | Open | +| `supplier_ref` | [shared.SupplierRef](../../models/shared/supplierref.md) | :heavy_check_mark: | Reference to the supplier the record relates to. | | +| `total_amount` | *Optional[Decimal]* | :heavy_minus_sign: | Amount of the bill, including tax. | | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/billaccountref.md b/sync-for-payables/docs/models/shared/billaccountref.md index 77f0c8d04..1188b06a2 100644 --- a/sync-for-payables/docs/models/shared/billaccountref.md +++ b/sync-for-payables/docs/models/shared/billaccountref.md @@ -1,10 +1,8 @@ -# BillAccountRef - -Reference to the account to which the line item is linked. - - -## Fields - -| Field | Type | Required | Description | -| --------------------------------- | --------------------------------- | --------------------------------- | --------------------------------- | +# BillAccountRef + + +## Fields + +| Field | Type | Required | Description | +| --------------------------------- | --------------------------------- | --------------------------------- | --------------------------------- | | `id` | *Optional[str]* | :heavy_minus_sign: | 'id' from the Accounts data type. | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/billdatatype.md b/sync-for-payables/docs/models/shared/billdatatype.md new file mode 100644 index 000000000..99441a657 --- /dev/null +++ b/sync-for-payables/docs/models/shared/billdatatype.md @@ -0,0 +1,17 @@ +# BillDataType + +## Example Usage + +```python +from codat_sync_for_payables.models.shared import BillDataType + +value = BillDataType.TRACKING_CATEGORIES +``` + + +## Values + +| Name | Value | +| --------------------- | --------------------- | +| `TRACKING_CATEGORIES` | trackingCategories | +| `CUSTOMERS` | customers | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/billeventpayload.md b/sync-for-payables/docs/models/shared/billeventpayload.md new file mode 100644 index 000000000..ec9189f17 --- /dev/null +++ b/sync-for-payables/docs/models/shared/billeventpayload.md @@ -0,0 +1,11 @@ +# BillEventPayload + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | +| `bill` | [Optional[shared.Bill]](../../models/shared/bill.md) | :heavy_minus_sign: | Bills are invoices that represent the SMB's financial obligations to their supplier for a purchase of goods or services. | | +| `company_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for your SMB in Codat. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `connection_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for a company's data connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | +| `push_operation_key` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for the push operation. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/billeventwebhook.md b/sync-for-payables/docs/models/shared/billeventwebhook.md new file mode 100644 index 000000000..5bbbadefe --- /dev/null +++ b/sync-for-payables/docs/models/shared/billeventwebhook.md @@ -0,0 +1,11 @@ +# BillEventWebhook + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | +| `created_date` | *Optional[str]* | :heavy_minus_sign: | The datetime in UTC of when the webhook event was produced by Codat. | 2022-10-23T11:03:35Z | +| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of the bill event. | | +| `payload` | [Optional[shared.BillEventPayload]](../../models/shared/billeventpayload.md) | :heavy_minus_sign: | N/A | | +| `type` | *Optional[str]* | :heavy_minus_sign: | Type of webhook event. | payables.bill.created | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/billlineitem.md b/sync-for-payables/docs/models/shared/billlineitem.md index 69d759c81..045654a10 100644 --- a/sync-for-payables/docs/models/shared/billlineitem.md +++ b/sync-for-payables/docs/models/shared/billlineitem.md @@ -1,15 +1,15 @@ -# BillLineItem - - -## Fields - -| Field | Type | Required | Description | -| ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | -| `description` | *OptionalNullable[str]* | :heavy_minus_sign: | Friendly name of the goods or services received. | -| `unit_amount` | *Optional[Decimal]* | :heavy_minus_sign: | Unit price of the goods or service. | -| `quantity` | *Optional[Decimal]* | :heavy_minus_sign: | Number of units of goods or services received. | -| `tax_amount` | *Optional[Decimal]* | :heavy_minus_sign: | Amount of tax applied to the line item. | -| `account_ref` | [Optional[shared.BillAccountRef]](../../models/shared/billaccountref.md) | :heavy_minus_sign: | Reference to the account to which the line item is linked. | -| `total_amount` | *OptionalNullable[Decimal]* | :heavy_minus_sign: | Total amount of the line, including tax. | -| `tax_rate_ref` | [Optional[shared.BillTaxRateRef]](../../models/shared/billtaxrateref.md) | :heavy_minus_sign: | Reference to the tax rate to which the line item is linked. | -| `tracking_refs` | List[[shared.TrackingRef](../../models/shared/trackingref.md)] | :heavy_minus_sign: | N/A | \ No newline at end of file +# BillLineItem + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | +| `account_ref` | [Optional[shared.BillAccountRef]](../../models/shared/billaccountref.md) | :heavy_minus_sign: | Reference to the account to which the line item is linked. | +| `description` | *OptionalNullable[str]* | :heavy_minus_sign: | Friendly name of the goods or services received. | +| `quantity` | *Optional[Decimal]* | :heavy_minus_sign: | Number of units of goods or services received. | +| `tax_amount` | *Optional[Decimal]* | :heavy_minus_sign: | Amount of tax applied to the line item. | +| `tax_rate_ref` | [Optional[shared.BillTaxRateRef]](../../models/shared/billtaxrateref.md) | :heavy_minus_sign: | Reference to the tax rate to which the line item is linked. | +| `total_amount` | *OptionalNullable[Decimal]* | :heavy_minus_sign: | Total amount of the line, including tax. | +| `tracking_refs` | List[[shared.TrackingRef](../../models/shared/trackingref.md)] | :heavy_minus_sign: | N/A | +| `unit_amount` | *Optional[Decimal]* | :heavy_minus_sign: | Unit price of the goods or service. | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/billmappingoptions.md b/sync-for-payables/docs/models/shared/billmappingoptions.md index e9979b159..f21b15a12 100644 --- a/sync-for-payables/docs/models/shared/billmappingoptions.md +++ b/sync-for-payables/docs/models/shared/billmappingoptions.md @@ -1,12 +1,12 @@ -# BillMappingOptions - -The bill mapping options for a company's accounting software. - - -## Fields - -| Field | Type | Required | Description | -| ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | -| `accounts` | List[[Nullable[shared.AccountMappingOption]](../../models/shared/accountmappingoption.md)] | :heavy_minus_sign: | N/A | -| `tax_rates` | List[[shared.TaxRateMappingOption](../../models/shared/taxratemappingoption.md)] | :heavy_minus_sign: | N/A | -| `pagination` | [Optional[shared.Pagination]](../../models/shared/pagination.md) | :heavy_minus_sign: | N/A | \ No newline at end of file +# BillMappingOptions + +The bill mapping options for a company's accounting software. + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | +| `accounts` | List[[Nullable[shared.AccountMappingOption]](../../models/shared/accountmappingoption.md)] | :heavy_minus_sign: | N/A | +| `pagination` | [Optional[shared.Pagination]](../../models/shared/pagination.md) | :heavy_minus_sign: | N/A | +| `tax_rates` | List[[shared.TaxRateMappingOption](../../models/shared/taxratemappingoption.md)] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/billpayment.md b/sync-for-payables/docs/models/shared/billpayment.md index 9ceaa2c30..e03d42642 100644 --- a/sync-for-payables/docs/models/shared/billpayment.md +++ b/sync-for-payables/docs/models/shared/billpayment.md @@ -1,13 +1,13 @@ -# BillPayment - - -## Fields - -| Field | Type | Required | Description | Example | -| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `id` | *Optional[str]* | :heavy_minus_sign: | Identifier for the bill payment, unique for the company in the accounting software. | | -| `amount` | *Optional[Decimal]* | :heavy_minus_sign: | Amount of the payment in the bill currency. | 1329.54 | -| `date_` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `reference` | *OptionalNullable[str]* | :heavy_minus_sign: | Additional information associated with the payment. | Bill Payment against bill c13e37b6-dfaa-4894-b3be-9fe97bda9f44 | -| `account_ref` | [Optional[shared.BillPaymentAccountRef]](../../models/shared/billpaymentaccountref.md) | :heavy_minus_sign: | Reference to the bank account / credit card which you are using to pay the bill. | | -| `currency_rate` | *OptionalNullable[Decimal]* | :heavy_minus_sign: | Rate to convert the total amount of the payment into the base currency for the company at the time of the payment.

Currency rates in Codat are implemented as the multiple of foreign currency units to each base currency unit.

It is not possible to perform the currency conversion with two or more non-base currencies participating in the transaction. For example, if a company's base currency is USD, and it has a bill issued in EUR, then the bill payment must happen in USD or EUR.

Where the currency rate is provided by the underlying accounting software, it will be available from Codat with the same precision (up to a maximum of 9 decimal places).

For accounting software which do not provide an explicit currency rate, it is calculated as `baseCurrency / foreignCurrency` and will be returned to 9 decimal places.

## Examples with base currency of GBP

\| Foreign Currency \| Foreign Amount \| Currency Rate \| Base Currency Amount (GBP) \|
\| :--------------- \| :------------- \| :------------ \| :------------------------- \|
\| **USD** \| $20 \| 0.781 \| £15.62 \|
\| **EUR** \| €20 \| 0.885 \| £17.70 \|
\| **RUB** \| ₽20 \| 0.011 \| £0.22 \|

## Examples with base currency of USD

\| Foreign Currency \| Foreign Amount \| Currency Rate \| Base Currency Amount (USD) \|
\| :--------------- \| :------------- \| :------------ \| :------------------------- \|
\| **GBP** \| £20 \| 1.277 \| $25.54 \|
\| **EUR** \| €20 \| 1.134 \| $22.68 \|
\| **RUB** \| ₽20 \| 0.015 \| $0.30 \|


### Integration-specific details

\| Integration \| Scenario \| System behavior \|
\|-------------------\|-------------------------------------------------\|----------------------------------------------------------------------------------------------------------------------------------------------------------------------\|
\| QuickBooks Online \| Transaction currency differs from base currency \| If currency rate value is left `null`, a rate of 1 will be used by QBO by default. To override this, specify a currencyRate in the request body. \| | | \ No newline at end of file +# BillPayment + + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `account_ref` | [Optional[shared.BillPaymentAccountRef]](../../models/shared/billpaymentaccountref.md) | :heavy_minus_sign: | Reference to the bank account / credit card which you are using to pay the bill. | | +| `amount` | *Optional[Decimal]* | :heavy_minus_sign: | Amount of the payment in the bill currency. | 1329.54 | +| `currency_rate` | *OptionalNullable[Decimal]* | :heavy_minus_sign: | Rate to convert the total amount of the payment into the base currency for the company at the time of the payment.

Currency rates in Codat are implemented as the multiple of foreign currency units to each base currency unit.

It is not possible to perform the currency conversion with two or more non-base currencies participating in the transaction. For example, if a company's base currency is USD, and it has a bill issued in EUR, then the bill payment must happen in USD or EUR.

Where the currency rate is provided by the underlying accounting software, it will be available from Codat with the same precision (up to a maximum of 9 decimal places).

For accounting software which do not provide an explicit currency rate, it is calculated as `baseCurrency / foreignCurrency` and will be returned to 9 decimal places.

## Examples with base currency of GBP

\| Foreign Currency \| Foreign Amount \| Currency Rate \| Base Currency Amount (GBP) \|
\| :--------------- \| :------------- \| :------------ \| :------------------------- \|
\| **USD** \| $20 \| 0.781 \| £15.62 \|
\| **EUR** \| €20 \| 0.885 \| £17.70 \|
\| **RUB** \| ₽20 \| 0.011 \| £0.22 \|

## Examples with base currency of USD

\| Foreign Currency \| Foreign Amount \| Currency Rate \| Base Currency Amount (USD) \|
\| :--------------- \| :------------- \| :------------ \| :------------------------- \|
\| **GBP** \| £20 \| 1.277 \| $25.54 \|
\| **EUR** \| €20 \| 1.134 \| $22.68 \|
\| **RUB** \| ₽20 \| 0.015 \| $0.30 \|


### Integration-specific details

\| Integration \| Scenario \| System behavior \|
\|-------------------\|-------------------------------------------------\|----------------------------------------------------------------------------------------------------------------------------------------------------------------------\|
\| QuickBooks Online \| Transaction currency differs from base currency \| If currency rate value is left `null`, a rate of 1 will be used by QBO by default. To override this, specify a currencyRate in the request body. \| | | +| `date_` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `id` | *Optional[str]* | :heavy_minus_sign: | Identifier for the bill payment, unique for the company in the accounting software. | | +| `reference` | *OptionalNullable[str]* | :heavy_minus_sign: | Additional information associated with the payment. | Bill Payment against bill c13e37b6-dfaa-4894-b3be-9fe97bda9f44 | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/billpaymentaccountref.md b/sync-for-payables/docs/models/shared/billpaymentaccountref.md index b8c1a4317..baf51b17f 100644 --- a/sync-for-payables/docs/models/shared/billpaymentaccountref.md +++ b/sync-for-payables/docs/models/shared/billpaymentaccountref.md @@ -1,10 +1,8 @@ -# BillPaymentAccountRef - -Reference to the bank account / credit card which you are using to pay the bill. - - -## Fields - -| Field | Type | Required | Description | -| ------------------------------------------- | ------------------------------------------- | ------------------------------------------- | ------------------------------------------- | +# BillPaymentAccountRef + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------- | ------------------------------------------- | ------------------------------------------- | ------------------------------------------- | | `id` | *str* | :heavy_check_mark: | Unique ID of the bank account / credit card | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/billpaymentprototype.md b/sync-for-payables/docs/models/shared/billpaymentprototype.md index dee200ee0..cfc0abade 100644 --- a/sync-for-payables/docs/models/shared/billpaymentprototype.md +++ b/sync-for-payables/docs/models/shared/billpaymentprototype.md @@ -1,12 +1,12 @@ -# BillPaymentPrototype - - -## Fields - -| Field | Type | Required | Description | Example | -| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `amount` | *Decimal* | :heavy_check_mark: | Amount of the payment in the bill currency. | 1329.54 | -| `date_` | *str* | :heavy_check_mark: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `reference` | *OptionalNullable[str]* | :heavy_minus_sign: | Additional information associated with the payment. | Bill Payment against bill c13e37b6-dfaa-4894-b3be-9fe97bda9f44 | -| `account_ref` | [shared.BillPaymentAccountRef](../../models/shared/billpaymentaccountref.md) | :heavy_check_mark: | Reference to the bank account / credit card which you are using to pay the bill. | | -| `currency_rate` | *OptionalNullable[Decimal]* | :heavy_minus_sign: | Rate to convert the total amount of the payment into the base currency for the company at the time of the payment.

Currency rates in Codat are implemented as the multiple of foreign currency units to each base currency unit.

It is not possible to perform the currency conversion with two or more non-base currencies participating in the transaction. For example, if a company's base currency is USD, and it has a bill issued in EUR, then the bill payment must happen in USD or EUR.

Where the currency rate is provided by the underlying accounting software, it will be available from Codat with the same precision (up to a maximum of 9 decimal places).

For accounting software which do not provide an explicit currency rate, it is calculated as `baseCurrency / foreignCurrency` and will be returned to 9 decimal places.

## Examples with base currency of GBP

\| Foreign Currency \| Foreign Amount \| Currency Rate \| Base Currency Amount (GBP) \|
\| :--------------- \| :------------- \| :------------ \| :------------------------- \|
\| **USD** \| $20 \| 0.781 \| £15.62 \|
\| **EUR** \| €20 \| 0.885 \| £17.70 \|
\| **RUB** \| ₽20 \| 0.011 \| £0.22 \|

## Examples with base currency of USD

\| Foreign Currency \| Foreign Amount \| Currency Rate \| Base Currency Amount (USD) \|
\| :--------------- \| :------------- \| :------------ \| :------------------------- \|
\| **GBP** \| £20 \| 1.277 \| $25.54 \|
\| **EUR** \| €20 \| 1.134 \| $22.68 \|
\| **RUB** \| ₽20 \| 0.015 \| $0.30 \|


### Integration-specific details

\| Integration \| Scenario \| System behavior \|
\|-------------------\|-------------------------------------------------\|----------------------------------------------------------------------------------------------------------------------------------------------------------------------\|
\| QuickBooks Online \| Transaction currency differs from base currency \| If currency rate value is left `null`, a rate of 1 will be used by QBO by default. To override this, specify a currencyRate in the request body. \| | | \ No newline at end of file +# BillPaymentPrototype + + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `account_ref` | [shared.BillPaymentAccountRef](../../models/shared/billpaymentaccountref.md) | :heavy_check_mark: | Reference to the bank account / credit card which you are using to pay the bill. | | +| `amount` | *Decimal* | :heavy_check_mark: | Amount of the payment in the bill currency. | 1329.54 | +| `currency_rate` | *OptionalNullable[Decimal]* | :heavy_minus_sign: | Rate to convert the total amount of the payment into the base currency for the company at the time of the payment.

Currency rates in Codat are implemented as the multiple of foreign currency units to each base currency unit.

It is not possible to perform the currency conversion with two or more non-base currencies participating in the transaction. For example, if a company's base currency is USD, and it has a bill issued in EUR, then the bill payment must happen in USD or EUR.

Where the currency rate is provided by the underlying accounting software, it will be available from Codat with the same precision (up to a maximum of 9 decimal places).

For accounting software which do not provide an explicit currency rate, it is calculated as `baseCurrency / foreignCurrency` and will be returned to 9 decimal places.

## Examples with base currency of GBP

\| Foreign Currency \| Foreign Amount \| Currency Rate \| Base Currency Amount (GBP) \|
\| :--------------- \| :------------- \| :------------ \| :------------------------- \|
\| **USD** \| $20 \| 0.781 \| £15.62 \|
\| **EUR** \| €20 \| 0.885 \| £17.70 \|
\| **RUB** \| ₽20 \| 0.011 \| £0.22 \|

## Examples with base currency of USD

\| Foreign Currency \| Foreign Amount \| Currency Rate \| Base Currency Amount (USD) \|
\| :--------------- \| :------------- \| :------------ \| :------------------------- \|
\| **GBP** \| £20 \| 1.277 \| $25.54 \|
\| **EUR** \| €20 \| 1.134 \| $22.68 \|
\| **RUB** \| ₽20 \| 0.015 \| $0.30 \|


### Integration-specific details

\| Integration \| Scenario \| System behavior \|
\|-------------------\|-------------------------------------------------\|----------------------------------------------------------------------------------------------------------------------------------------------------------------------\|
\| QuickBooks Online \| Transaction currency differs from base currency \| If currency rate value is left `null`, a rate of 1 will be used by QBO by default. To override this, specify a currencyRate in the request body. \| | | +| `date_` | *str* | :heavy_check_mark: | Date the bill payment was recorded in the accounting software. | | +| `reference` | *OptionalNullable[str]* | :heavy_minus_sign: | Additional information associated with the payment. | Bill Payment against bill c13e37b6-dfaa-4894-b3be-9fe97bda9f44 | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/billprototype.md b/sync-for-payables/docs/models/shared/billprototype.md index 1b924b241..35ac40d58 100644 --- a/sync-for-payables/docs/models/shared/billprototype.md +++ b/sync-for-payables/docs/models/shared/billprototype.md @@ -1,15 +1,15 @@ -# BillPrototype - - -## Fields - -| Field | Type | Required | Description | Example | -| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `reference` | *OptionalNullable[str]* | :heavy_minus_sign: | User-friendly reference for the bill. | | -| `supplier_ref` | [shared.SupplierRef](../../models/shared/supplierref.md) | :heavy_check_mark: | Reference to the supplier the record relates to. | | -| `issue_date` | *str* | :heavy_check_mark: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `due_date` | *str* | :heavy_check_mark: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `currency` | *str* | :heavy_check_mark: | The currency data type in Codat is the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code, e.g. _GBP_.

## Unknown currencies

In line with the ISO 4217 specification, the code _XXX_ is used when the data source does not return a currency for a transaction.

There are only a very small number of edge cases where this currency code is returned by the Codat system. | **Example 1:** GBP
**Example 2:** USD
**Example 3:** EUR | -| `currency_rate` | *OptionalNullable[Decimal]* | :heavy_minus_sign: | Rate to convert the total amount of the payment into the base currency for the company at the time of the payment.

Currency rates in Codat are implemented as the multiple of foreign currency units to each base currency unit.

It is not possible to perform the currency conversion with two or more non-base currencies participating in the transaction. For example, if a company's base currency is USD, and it has a bill issued in EUR, then the bill payment must happen in USD or EUR.

Where the currency rate is provided by the underlying accounting software, it will be available from Codat with the same precision (up to a maximum of 9 decimal places).

For accounting software which do not provide an explicit currency rate, it is calculated as `baseCurrency / foreignCurrency` and will be returned to 9 decimal places.

## Examples with base currency of GBP

\| Foreign Currency \| Foreign Amount \| Currency Rate \| Base Currency Amount (GBP) \|
\| :--------------- \| :------------- \| :------------ \| :------------------------- \|
\| **USD** \| $20 \| 0.781 \| £15.62 \|
\| **EUR** \| €20 \| 0.885 \| £17.70 \|
\| **RUB** \| ₽20 \| 0.011 \| £0.22 \|

## Examples with base currency of USD

\| Foreign Currency \| Foreign Amount \| Currency Rate \| Base Currency Amount (USD) \|
\| :--------------- \| :------------- \| :------------ \| :------------------------- \|
\| **GBP** \| £20 \| 1.277 \| $25.54 \|
\| **EUR** \| €20 \| 1.134 \| $22.68 \|
\| **RUB** \| ₽20 \| 0.015 \| $0.30 \|


### Integration-specific details

\| Integration \| Scenario \| System behavior \|
\|-------------------\|-------------------------------------------------\|----------------------------------------------------------------------------------------------------------------------------------------------------------------------\|
\| QuickBooks Online \| Transaction currency differs from base currency \| If currency rate value is left `null`, a rate of 1 will be used by QBO by default. To override this, specify a currencyRate in the request body. \| | | -| `line_items` | List[[shared.BillLineItem](../../models/shared/billlineitem.md)] | :heavy_minus_sign: | Array of Bill line items. | | -| `status` | [shared.BillStatus](../../models/shared/billstatus.md) | :heavy_check_mark: | Current state of the bill. If creating a bill the status must be `Open`. | Open | \ No newline at end of file +# BillPrototype + + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `currency` | *str* | :heavy_check_mark: | The currency data type in Codat is the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code, e.g. _GBP_.

## Unknown currencies

In line with the ISO 4217 specification, the code _XXX_ is used when the data source does not return a currency for a transaction.

There are only a very small number of edge cases where this currency code is returned by the Codat system. | **Example 1:** GBP
**Example 2:** USD
**Example 3:** EUR | +| `currency_rate` | *OptionalNullable[Decimal]* | :heavy_minus_sign: | Rate to convert the total amount of the payment into the base currency for the company at the time of the payment.

Currency rates in Codat are implemented as the multiple of foreign currency units to each base currency unit.

It is not possible to perform the currency conversion with two or more non-base currencies participating in the transaction. For example, if a company's base currency is USD, and it has a bill issued in EUR, then the bill payment must happen in USD or EUR.

Where the currency rate is provided by the underlying accounting software, it will be available from Codat with the same precision (up to a maximum of 9 decimal places).

For accounting software which do not provide an explicit currency rate, it is calculated as `baseCurrency / foreignCurrency` and will be returned to 9 decimal places.

## Examples with base currency of GBP

\| Foreign Currency \| Foreign Amount \| Currency Rate \| Base Currency Amount (GBP) \|
\| :--------------- \| :------------- \| :------------ \| :------------------------- \|
\| **USD** \| $20 \| 0.781 \| £15.62 \|
\| **EUR** \| €20 \| 0.885 \| £17.70 \|
\| **RUB** \| ₽20 \| 0.011 \| £0.22 \|

## Examples with base currency of USD

\| Foreign Currency \| Foreign Amount \| Currency Rate \| Base Currency Amount (USD) \|
\| :--------------- \| :------------- \| :------------ \| :------------------------- \|
\| **GBP** \| £20 \| 1.277 \| $25.54 \|
\| **EUR** \| €20 \| 1.134 \| $22.68 \|
\| **RUB** \| ₽20 \| 0.015 \| $0.30 \|


### Integration-specific details

\| Integration \| Scenario \| System behavior \|
\|-------------------\|-------------------------------------------------\|----------------------------------------------------------------------------------------------------------------------------------------------------------------------\|
\| QuickBooks Online \| Transaction currency differs from base currency \| If currency rate value is left `null`, a rate of 1 will be used by QBO by default. To override this, specify a currencyRate in the request body. \| | | +| `due_date` | *str* | :heavy_check_mark: | Date the supplier is due to be paid. | | +| `issue_date` | *str* | :heavy_check_mark: | Date of the bill as recorded in the accounting software. | | +| `line_items` | List[[shared.BillLineItem](../../models/shared/billlineitem.md)] | :heavy_minus_sign: | Array of Bill line items. | | +| `reference` | *OptionalNullable[str]* | :heavy_minus_sign: | User-friendly reference for the bill. | | +| `status` | [shared.BillStatus](../../models/shared/billstatus.md) | :heavy_check_mark: | Current state of the bill. If creating a bill the status must be `Open`. | Open | +| `supplier_ref` | [shared.SupplierRef](../../models/shared/supplierref.md) | :heavy_check_mark: | Reference to the supplier the record relates to. | | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/bills.md b/sync-for-payables/docs/models/shared/bills.md index 58122acd2..b22a8fe1d 100644 --- a/sync-for-payables/docs/models/shared/bills.md +++ b/sync-for-payables/docs/models/shared/bills.md @@ -1,9 +1,9 @@ -# Bills - - -## Fields - -| Field | Type | Required | Description | -| ---------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------- | -| `results` | List[[shared.Bill](../../models/shared/bill.md)] | :heavy_minus_sign: | N/A | -| `pagination` | [Optional[shared.Pagination]](../../models/shared/pagination.md) | :heavy_minus_sign: | N/A | \ No newline at end of file +# Bills + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------- | +| `pagination` | [Optional[shared.Pagination]](../../models/shared/pagination.md) | :heavy_minus_sign: | N/A | +| `results` | List[[shared.Bill](../../models/shared/bill.md)] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/billstatus.md b/sync-for-payables/docs/models/shared/billstatus.md index f3991cbb0..6fe4874e1 100644 --- a/sync-for-payables/docs/models/shared/billstatus.md +++ b/sync-for-payables/docs/models/shared/billstatus.md @@ -1,23 +1,21 @@ -# BillStatus - -Current state of the bill. If creating a bill the status must be `Open`. - -## Example Usage - -```python -from codat_sync_for_payables.models.shared import BillStatus - -value = BillStatus.UNKNOWN -``` - - -## Values - -| Name | Value | -| ---------------- | ---------------- | -| `UNKNOWN` | Unknown | -| `OPEN` | Open | -| `PARTIALLY_PAID` | PartiallyPaid | -| `PAID` | Paid | -| `VOID` | Void | +# BillStatus + +## Example Usage + +```python +from codat_sync_for_payables.models.shared import BillStatus + +value = BillStatus.UNKNOWN +``` + + +## Values + +| Name | Value | +| ---------------- | ---------------- | +| `UNKNOWN` | Unknown | +| `OPEN` | Open | +| `PARTIALLY_PAID` | PartiallyPaid | +| `PAID` | Paid | +| `VOID` | Void | | `DRAFT` | Draft | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/billtaxrateref.md b/sync-for-payables/docs/models/shared/billtaxrateref.md index 28d67e255..0a4a1ad04 100644 --- a/sync-for-payables/docs/models/shared/billtaxrateref.md +++ b/sync-for-payables/docs/models/shared/billtaxrateref.md @@ -1,10 +1,8 @@ -# BillTaxRateRef - -Reference to the tax rate to which the line item is linked. - - -## Fields - -| Field | Type | Required | Description | -| -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | +# BillTaxRateRef + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | | `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for the tax rate in the accounting software. | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/clientratelimitwebhook.md b/sync-for-payables/docs/models/shared/clientratelimitwebhook.md new file mode 100644 index 000000000..8ecf1141e --- /dev/null +++ b/sync-for-payables/docs/models/shared/clientratelimitwebhook.md @@ -0,0 +1,11 @@ +# ClientRateLimitWebhook + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `event_type` | *Optional[str]* | :heavy_minus_sign: | The type of event. | **Example 1:** client.rateLimit.reset
**Example 2:** client.rateLimit.reached | +| `generated_date` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of the event. | 743ec94a-8aa4-44bb-8bd4-e1855ee0e74b | +| `payload` | [Optional[shared.ClientRateLimitWebhookPayload]](../../models/shared/clientratelimitwebhookpayload.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/clientratelimitwebhookpayload.md b/sync-for-payables/docs/models/shared/clientratelimitwebhookpayload.md new file mode 100644 index 000000000..ae6051b29 --- /dev/null +++ b/sync-for-payables/docs/models/shared/clientratelimitwebhookpayload.md @@ -0,0 +1,10 @@ +# ClientRateLimitWebhookPayload + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `daily_quota` | *Optional[int]* | :heavy_minus_sign: | The number of available requests per day. | | +| `expiry_date` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `quota_remaining` | *Optional[int]* | :heavy_minus_sign: | Total number of requests remaining for your client. | | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/codatfile.md b/sync-for-payables/docs/models/shared/codatfile.md index 891a552ad..3eba70262 100644 --- a/sync-for-payables/docs/models/shared/codatfile.md +++ b/sync-for-payables/docs/models/shared/codatfile.md @@ -1,10 +1,10 @@ -# CodatFile - - -## Fields - -| Field | Type | Required | Description | -| -------------------------------------------- | -------------------------------------------- | -------------------------------------------- | -------------------------------------------- | -| `file_name` | *str* | :heavy_check_mark: | N/A | -| `content` | *Union[bytes, IO[bytes], io.BufferedReader]* | :heavy_check_mark: | N/A | -| `content_type` | *Optional[str]* | :heavy_minus_sign: | N/A | \ No newline at end of file +# CodatFile + + +## Fields + +| Field | Type | Required | Description | +| ------------------------- | ------------------------- | ------------------------- | ------------------------- | +| `content` | *Union[bytes, IO[bytes]]* | :heavy_check_mark: | N/A | +| `content_type` | *Optional[str]* | :heavy_minus_sign: | N/A | +| `file_name` | *str* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/companies.md b/sync-for-payables/docs/models/shared/companies.md index 6436dc2cd..a4a43b1c2 100644 --- a/sync-for-payables/docs/models/shared/companies.md +++ b/sync-for-payables/docs/models/shared/companies.md @@ -1,12 +1,12 @@ -# Companies - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | -| `results` | List[[shared.Company](../../models/shared/company.md)] | :heavy_minus_sign: | N/A | | -| `page_number` | *int* | :heavy_check_mark: | Current page number. | | -| `page_size` | *int* | :heavy_check_mark: | Number of items to return in results array. | | -| `total_results` | *int* | :heavy_check_mark: | Total number of items. | | -| `links` | [shared.Links](../../models/shared/links.md) | :heavy_check_mark: | N/A | {
"self": {
"href": "/companies"
},
"current": {
"href": "/companies?page=1\u0026pageSize=10"
}
} | \ No newline at end of file +# Companies + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| `links` | [shared.Links](../../models/shared/links.md) | :heavy_check_mark: | N/A | {
"self": {
"href": "/companies"
},
"current": {
"href": "/companies?page=1\u0026pageSize=10"
}
} | +| `page_number` | *int* | :heavy_check_mark: | Current page number. | | +| `page_size` | *int* | :heavy_check_mark: | Number of items to return in results array. | | +| `results` | List[[shared.Company](../../models/shared/company.md)] | :heavy_minus_sign: | N/A | | +| `total_results` | *int* | :heavy_check_mark: | Total number of items. | | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/company.md b/sync-for-payables/docs/models/shared/company.md index 02b633fb4..a28cea881 100644 --- a/sync-for-payables/docs/models/shared/company.md +++ b/sync-for-payables/docs/models/shared/company.md @@ -1,25 +1,25 @@ -# Company - -In Codat, a company represents a business sharing access to their data. Each company can have multiple [connections](https://docs.codat.io/sync-for-payables-api#/schemas/Connection) to different data sources such as one connection to [Xero](https://docs.codat.io/integrations/accounting/xero/accounting-xero) for accounting data, two connections to [Plaid](https://docs.codat.io/integrations/banking/plaid/banking-plaid) for two bank accounts and a connection to [Zettle](https://docs.codat.io/integrations/commerce/zettle/commerce-zettle) for POS data. - -Typically each company is one of your customers. - -When you create a company, you can specify a `name` and we will automatically generate a unique `id` for the company. You can also add a `description` to store any additional information about the company. - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `id` | *str* | :heavy_check_mark: | Unique identifier for your SMB in Codat. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `name` | *str* | :heavy_check_mark: | The name of the company | Codat Ltd. | -| `description` | *Optional[str]* | :heavy_minus_sign: | Additional information about the company. This can be used to store foreign IDs, references, etc. | Requested early access to the new financing scheme. | -| `redirect` | *str* | :heavy_check_mark: | The `redirect` [Link URL](https://docs.codat.io/auth-flow/authorize-hosted-link) enabling the customer to start their auth flow journey for the company. | https://link.codat.io/company/27628208-459c-46a2-a705-5641ce25f739 | -| `last_sync` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `created` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `created_by_user_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of user that created the company in Codat. | | -| `products` | List[*str*] | :heavy_minus_sign: | An array of products that are currently enabled for the company. | | -| `tags` | Dict[str, *str*] | :heavy_minus_sign: | A collection of user-defined key-value pairs that store custom metadata against the company. | | -| `reference_parent_company` | [Optional[shared.CompanyReference]](../../models/shared/companyreference.md) | :heavy_minus_sign: | N/A | | -| `reference_subsidiary_companies` | List[[shared.CompanyReference](../../models/shared/companyreference.md)] | :heavy_minus_sign: | A list of subsidiary companies owned or controlled by this entity. Empty if the company has no children. | | -| `data_connections` | List[[shared.Connection](../../models/shared/connection.md)] | :heavy_minus_sign: | N/A | | \ No newline at end of file +# Company + +In Codat, a company represents a business sharing access to their data. Each company can have multiple [connections](https://docs.codat.io/sync-for-payables-api#/schemas/Connection) to different data sources such as one connection to [Xero](https://docs.codat.io/integrations/accounting/xero/accounting-xero) for accounting data, two connections to [Plaid](https://docs.codat.io/integrations/banking/plaid/banking-plaid) for two bank accounts and a connection to [Zettle](https://docs.codat.io/integrations/commerce/zettle/commerce-zettle) for POS data. + +Typically each company is one of your customers. + +When you create a company, you can specify a `name` and we will automatically generate a unique `id` for the company. You can also add a `description` to store any additional information about the company. + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `created` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `created_by_user_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of user that created the company in Codat. | | +| `data_connections` | List[[shared.Connection](../../models/shared/connection.md)] | :heavy_minus_sign: | N/A | | +| `description` | *Optional[str]* | :heavy_minus_sign: | Additional information about the company. This can be used to store foreign IDs, references, etc. | Requested early access to the new financing scheme. | +| `id` | *str* | :heavy_check_mark: | Unique identifier for your SMB in Codat. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `last_sync` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `name` | *str* | :heavy_check_mark: | The name of the company | Codat Ltd. | +| `products` | List[*str*] | :heavy_minus_sign: | An array of products that are currently enabled for the company. | | +| `redirect` | *str* | :heavy_check_mark: | The `redirect` [Link URL](https://docs.codat.io/auth-flow/authorize-hosted-link) enabling the customer to start their auth flow journey for the company. | https://link.codat.io/company/27628208-459c-46a2-a705-5641ce25f739 | +| `reference_parent_company` | [Optional[shared.CompanyReference]](../../models/shared/companyreference.md) | :heavy_minus_sign: | The parent entity or controlling organization of this company. Null if the company has no parent. | | +| `reference_subsidiary_companies` | List[[shared.CompanyReference](../../models/shared/companyreference.md)] | :heavy_minus_sign: | A list of subsidiary companies owned or controlled by this entity. Empty if the company has no children. | | +| `tags` | Dict[str, *str*] | :heavy_minus_sign: | A collection of user-defined key-value pairs that store custom metadata against the company. | | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/companydetails.md b/sync-for-payables/docs/models/shared/companydetails.md new file mode 100644 index 000000000..ec8efb694 --- /dev/null +++ b/sync-for-payables/docs/models/shared/companydetails.md @@ -0,0 +1,18 @@ +# CompanyDetails + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `created` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `created_by_user_name` | *Optional[str]* | :heavy_minus_sign: | Name of user that created the company in Codat. | | +| `description` | *Optional[str]* | :heavy_minus_sign: | Additional information about the company. This can be used to store foreign IDs, references, etc. | Requested early access to the new financing scheme. | +| `id` | *str* | :heavy_check_mark: | Unique identifier for your SMB in Codat. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `last_sync` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `name` | *str* | :heavy_check_mark: | The name of the company | Codat Ltd. | +| `products` | List[*str*] | :heavy_minus_sign: | An array of products that are currently enabled for the company. | | +| `redirect` | *str* | :heavy_check_mark: | The `redirect` [Link URL](https://docs.codat.io/auth-flow/authorize-hosted-link) enabling the customer to start their auth flow journey for the company. | https://link.codat.io/company/27628208-459c-46a2-a705-5641ce25f739 | +| `reference_parent_company` | [Optional[shared.CompanyReference]](../../models/shared/companyreference.md) | :heavy_minus_sign: | The parent entity or controlling organization of this company. Null if the company has no parent. | | +| `reference_subsidiary_companies` | List[[shared.CompanyReference](../../models/shared/companyreference.md)] | :heavy_minus_sign: | A list of subsidiary companies owned or controlled by this entity. Empty if the company has no children. | | +| `tags` | Dict[str, *str*] | :heavy_minus_sign: | A collection of user-defined key-value pairs that store custom metadata against the company. | | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/companyinformation.md b/sync-for-payables/docs/models/shared/companyinformation.md index 387fdc506..738d98858 100644 --- a/sync-for-payables/docs/models/shared/companyinformation.md +++ b/sync-for-payables/docs/models/shared/companyinformation.md @@ -1,11 +1,11 @@ -# CompanyInformation - -Gets the latest basic info for a company. - - -## Fields - -| Field | Type | Required | Description | -| ----------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | -| `company_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the linked company. | -| `base_currency` | *OptionalNullable[str]* | :heavy_minus_sign: | Currency set in the accounting software of the linked company. Used by the currency rate. | \ No newline at end of file +# CompanyInformation + +Gets the latest basic info for a company. + + +## Fields + +| Field | Type | Required | Description | +| ----------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | +| `base_currency` | *OptionalNullable[str]* | :heavy_minus_sign: | Currency set in the accounting software of the linked company. Used by the currency rate. | +| `company_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the linked company. | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/companyreference.md b/sync-for-payables/docs/models/shared/companyreference.md index bb9cd0dd4..97b15c6bc 100644 --- a/sync-for-payables/docs/models/shared/companyreference.md +++ b/sync-for-payables/docs/models/shared/companyreference.md @@ -1,12 +1,12 @@ -# CompanyReference - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | -| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for your SMB in Codat. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `name` | *Optional[str]* | :heavy_minus_sign: | The name of the company | Codat Ltd. | -| `description` | *Optional[str]* | :heavy_minus_sign: | Additional information about the company. This can be used to store foreign IDs, references, etc. | Requested early access to the new financing scheme. | -| `links` | [Optional[shared.CompanyReferenceLinks]](../../models/shared/companyreferencelinks.md) | :heavy_minus_sign: | A collection of links for the company. | | +# CompanyReference + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| `description` | *Optional[str]* | :heavy_minus_sign: | Additional information about the company. This can be used to store foreign IDs, references, etc. | Requested early access to the new financing scheme. | +| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for your SMB in Codat. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `links` | [Optional[shared.CompanyReferenceLinks]](../../models/shared/companyreferencelinks.md) | :heavy_minus_sign: | A collection of links for the company. | | +| `name` | *Optional[str]* | :heavy_minus_sign: | The name of the company | Codat Ltd. | | `tags` | Dict[str, *str*] | :heavy_minus_sign: | A collection of user-defined key-value pairs that store custom metadata against the company. | | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/companyreferencelinks.md b/sync-for-payables/docs/models/shared/companyreferencelinks.md index ee01fd320..a4c491724 100644 --- a/sync-for-payables/docs/models/shared/companyreferencelinks.md +++ b/sync-for-payables/docs/models/shared/companyreferencelinks.md @@ -1,10 +1,10 @@ -# CompanyReferenceLinks - -A collection of links for the company. - - -## Fields - -| Field | Type | Required | Description | -| --------------------------------------- | --------------------------------------- | --------------------------------------- | --------------------------------------- | +# CompanyReferenceLinks + +A collection of links for the company. + + +## Fields + +| Field | Type | Required | Description | +| --------------------------------------- | --------------------------------------- | --------------------------------------- | --------------------------------------- | | `portal` | *Optional[str]* | :heavy_minus_sign: | Link to the company page in the portal. | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/companyrequestbody.md b/sync-for-payables/docs/models/shared/companyrequestbody.md index 3b85563a1..107790e6e 100644 --- a/sync-for-payables/docs/models/shared/companyrequestbody.md +++ b/sync-for-payables/docs/models/shared/companyrequestbody.md @@ -1,10 +1,10 @@ -# CompanyRequestBody - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | -| `name` | *str* | :heavy_check_mark: | Name of company being connected. | Bank of Dave | -| `description` | *Optional[str]* | :heavy_minus_sign: | Additional information about the company. This can be used to store foreign IDs, references, etc. | Requested early access to the new financing scheme. | +# CompanyRequestBody + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| `description` | *Optional[str]* | :heavy_minus_sign: | Additional information about the company. This can be used to store foreign IDs, references, etc. | Requested early access to the new financing scheme. | +| `name` | *str* | :heavy_check_mark: | Name of company being connected. | Bank of Dave | | `tags` | Dict[str, *str*] | :heavy_minus_sign: | A collection of user-defined key-value pairs that store custom metadata against the company. | | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/companyupdaterequest.md b/sync-for-payables/docs/models/shared/companyupdaterequest.md index 80229fd64..1ae031209 100644 --- a/sync-for-payables/docs/models/shared/companyupdaterequest.md +++ b/sync-for-payables/docs/models/shared/companyupdaterequest.md @@ -1,10 +1,10 @@ -# CompanyUpdateRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | -| `name` | *Optional[str]* | :heavy_minus_sign: | Name of company being connected. | Bank of Dave | -| `description` | *Optional[str]* | :heavy_minus_sign: | Additional information about the company. This can be used to store foreign IDs, references, etc. | Requested early access to the new financing scheme. | +# CompanyUpdateRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| `description` | *Optional[str]* | :heavy_minus_sign: | Additional information about the company. This can be used to store foreign IDs, references, etc. | Requested early access to the new financing scheme. | +| `name` | *Optional[str]* | :heavy_minus_sign: | Name of company being connected. | Bank of Dave | | `tags` | Dict[str, *str*] | :heavy_minus_sign: | A collection of user-defined key-value pairs that store custom metadata against the company. | | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/connection.md b/sync-for-payables/docs/models/shared/connection.md index 32e3b4b5b..c97264b66 100644 --- a/sync-for-payables/docs/models/shared/connection.md +++ b/sync-for-payables/docs/models/shared/connection.md @@ -1,30 +1,31 @@ -# Connection - -A connection represents a [company's](https://docs.codat.io/sync-for-payables-api#/schemas/Company) connection to a data source and allows you to synchronize data (pull and/or push) with that source. - -A company can have multiple data connections depending on the type of data source it is connecting to. For example, a single company can link to: - -- [Accounting data](https://docs.codat.io/accounting-api/overview) - 1 active connection. -- [Banking data](https://docs.codat.io/banking-api/overview) - Multiple active connections. -- [Commerce data](https://docs.codat.io/commerce-api/overview) - Multiple active connections. -Any combination of accounting, banking, and commerce data connections is allowed. - -Before you can use a data connection to pull or push data, the company must grant you access to their business data by [linking the connection](https://docs.codat.io/auth-flow/overview). - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `id` | *str* | :heavy_check_mark: | Unique identifier for a company's data connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | -| `integration_id` | *str* | :heavy_check_mark: | A Codat ID representing the integration. | fd321cb6-7963-4506-b873-e99593a45e30 | -| `integration_key` | *Optional[str]* | :heavy_minus_sign: | A unique four-character ID that identifies the platform of the company's data connection. This ensures continuity if the platform changes its name in the future. | | -| `source_id` | *str* | :heavy_check_mark: | A source-specific ID used to distinguish between different sources originating from the same data connection. In general, a data connection is a single data source. However, for TrueLayer, `sourceId` is associated with a specific bank and has a many-to-one relationship with the `integrationId`. | 35b92968-9851-4095-ad60-395c95cbcba4 | -| `source_type` | [shared.SourceType](../../models/shared/sourcetype.md) | :heavy_check_mark: | The type of platform of the connection. | Accounting | -| `platform_name` | *str* | :heavy_check_mark: | Name of integration connected to company. | | -| `link_url` | *str* | :heavy_check_mark: | The link URL your customers can use to authorize access to their business application. | https://link-api.codat.io/companies/86bd88cb-44ab-4dfb-b32f-87b19b14287f/connections/2e2eb431-c1fa-4dc9-93fa-d29781c12bcd/start | -| `status` | [shared.DataConnectionStatus](../../models/shared/dataconnectionstatus.md) | :heavy_check_mark: | The current authorization status of the data connection. | | -| `last_sync` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `created` | *str* | :heavy_check_mark: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `data_connection_errors` | List[[shared.DataConnectionError](../../models/shared/dataconnectionerror.md)] | :heavy_minus_sign: | N/A | | -| `connection_info` | Dict[str, *Any*] | :heavy_minus_sign: | N/A | | \ No newline at end of file +# Connection + +A connection represents a [company's](https://docs.codat.io/sync-for-payables-api#/schemas/Company) connection to a data source and allows you to synchronize data (pull and/or push) with that source. + +A company can have multiple data connections depending on the type of data source it is connecting to. For example, a single company can link to: + +- [Accounting data](https://docs.codat.io/accounting-api/overview) - 1 active connection. +- [Banking data](https://docs.codat.io/banking-api/overview) - Multiple active connections. +- [Commerce data](https://docs.codat.io/commerce-api/overview) - Multiple active connections. +Any combination of accounting, banking, and commerce data connections is allowed. + +Before you can use a data connection to pull or push data, the company must grant you access to their business data by [linking the connection](https://docs.codat.io/auth-flow/overview). + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `additional_properties` | Dict[str, *Any*] | :heavy_check_mark: | N/A | | +| `connection_info` | Dict[str, *Any*] | :heavy_minus_sign: | N/A | | +| `created` | *str* | :heavy_check_mark: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `data_connection_errors` | List[[shared.DataConnectionError](../../models/shared/dataconnectionerror.md)] | :heavy_minus_sign: | N/A | | +| `id` | *str* | :heavy_check_mark: | Unique identifier for a company's data connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | +| `integration_id` | *str* | :heavy_check_mark: | A Codat ID representing the integration. | fd321cb6-7963-4506-b873-e99593a45e30 | +| `integration_key` | *Optional[str]* | :heavy_minus_sign: | A unique four-character ID that identifies the platform of the company's data connection. This ensures continuity if the platform changes its name in the future. | | +| `last_sync` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `link_url` | *str* | :heavy_check_mark: | The link URL your customers can use to authorize access to their business application. | https://link-api.codat.io/companies/86bd88cb-44ab-4dfb-b32f-87b19b14287f/connections/2e2eb431-c1fa-4dc9-93fa-d29781c12bcd/start | +| `platform_name` | *str* | :heavy_check_mark: | Name of integration connected to company. | | +| `source_id` | *str* | :heavy_check_mark: | A source-specific ID used to distinguish between different sources originating from the same data connection. In general, a data connection is a single data source. However, for TrueLayer, `sourceId` is associated with a specific bank and has a many-to-one relationship with the `integrationId`. | 35b92968-9851-4095-ad60-395c95cbcba4 | +| `source_type` | [shared.SourceType](../../models/shared/sourcetype.md) | :heavy_check_mark: | The type of platform of the connection. | Accounting | +| `status` | [shared.DataConnectionStatus](../../models/shared/dataconnectionstatus.md) | :heavy_check_mark: | The current authorization status of the data connection. | | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/connections.md b/sync-for-payables/docs/models/shared/connections.md index ea48ba61e..29a1b8ed3 100644 --- a/sync-for-payables/docs/models/shared/connections.md +++ b/sync-for-payables/docs/models/shared/connections.md @@ -1,12 +1,12 @@ -# Connections - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | -| `results` | List[[shared.Connection](../../models/shared/connection.md)] | :heavy_minus_sign: | N/A | | -| `page_number` | *int* | :heavy_check_mark: | Current page number. | | -| `page_size` | *int* | :heavy_check_mark: | Number of items to return in results array. | | -| `total_results` | *int* | :heavy_check_mark: | Total number of items. | | -| `links` | [shared.Links](../../models/shared/links.md) | :heavy_check_mark: | N/A | {
"self": {
"href": "/companies"
},
"current": {
"href": "/companies?page=1\u0026pageSize=10"
}
} | \ No newline at end of file +# Connections + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| `links` | [shared.Links](../../models/shared/links.md) | :heavy_check_mark: | N/A | {
"self": {
"href": "/companies"
},
"current": {
"href": "/companies?page=1\u0026pageSize=10"
}
} | +| `page_number` | *int* | :heavy_check_mark: | Current page number. | | +| `page_size` | *int* | :heavy_check_mark: | Number of items to return in results array. | | +| `results` | List[[shared.Connection](../../models/shared/connection.md)] | :heavy_minus_sign: | N/A | | +| `total_results` | *int* | :heavy_check_mark: | Total number of items. | | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/createconnectionrequest.md b/sync-for-payables/docs/models/shared/createconnectionrequest.md new file mode 100644 index 000000000..dcf930d2f --- /dev/null +++ b/sync-for-payables/docs/models/shared/createconnectionrequest.md @@ -0,0 +1,8 @@ +# CreateConnectionRequest + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `platform_key` | *Optional[str]* | :heavy_minus_sign: | A unique 4-letter key to represent a platform in each integration. View [accounting](https://docs.codat.io/integrations/accounting/overview#platform-keys), [banking](https://docs.codat.io/integrations/banking/overview#platform-keys), and [commerce](https://docs.codat.io/integrations/commerce/overview#platform-keys) platform keys. | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/currentstatus.md b/sync-for-payables/docs/models/shared/currentstatus.md new file mode 100644 index 000000000..a6403a505 --- /dev/null +++ b/sync-for-payables/docs/models/shared/currentstatus.md @@ -0,0 +1,36 @@ +# CurrentStatus + +## Example Usage + +```python +from codat_sync_for_payables.models.shared import CurrentStatus + +value = CurrentStatus.INITIAL +``` + + +## Values + +| Name | Value | +| ---------------------- | ---------------------- | +| `INITIAL` | Initial | +| `QUEUED` | Queued | +| `FETCHING` | Fetching | +| `MAP_QUEUED` | MapQueued | +| `MAPPING` | Mapping | +| `COMPLETE` | Complete | +| `FETCH_ERROR` | FetchError | +| `MAP_ERROR` | MapError | +| `INTERNAL_ERROR` | InternalError | +| `PROCESSING_QUEUED` | ProcessingQueued | +| `PROCESSING` | Processing | +| `PROCESSING_ERROR` | ProcessingError | +| `VALIDATION_QUEUED` | ValidationQueued | +| `VALIDATING` | Validating | +| `VALIDATION_ERROR` | ValidationError | +| `AUTH_ERROR` | AuthError | +| `CANCELLED` | Cancelled | +| `NOT_SUPPORTED` | NotSupported | +| `RATE_LIMIT_ERROR` | RateLimitError | +| `PERMISSIONS_ERROR` | PermissionsError | +| `PREREQUISITE_NOT_MET` | PrerequisiteNotMet | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/dataconnectionerror.md b/sync-for-payables/docs/models/shared/dataconnectionerror.md index e381d128e..96b4828fa 100644 --- a/sync-for-payables/docs/models/shared/dataconnectionerror.md +++ b/sync-for-payables/docs/models/shared/dataconnectionerror.md @@ -1,13 +1,13 @@ -# DataConnectionError - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `status_code` | *Optional[str]* | :heavy_minus_sign: | The HTTP status code returned by the source platform when the error occurred. | | -| `status_text` | *Optional[str]* | :heavy_minus_sign: | A non-numeric status code/text returned by the source platform when the error occurred. | | -| `error_message` | *Optional[str]* | :heavy_minus_sign: | A message about a error returned by Codat. | | -| `errored_on_utc` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `status` | [OptionalNullable[shared.ErrorStatus]](../../models/shared/errorstatus.md) | :heavy_minus_sign: | The current status of a transient error. Null statuses indicate that the error is not transient. | | -| `resolved_on_utc` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | \ No newline at end of file +# DataConnectionError + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `error_message` | *Optional[str]* | :heavy_minus_sign: | A message about a error returned by Codat. | | +| `errored_on_utc` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `resolved_on_utc` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `status` | [OptionalNullable[shared.ErrorStatus]](../../models/shared/errorstatus.md) | :heavy_minus_sign: | The current status of a transient error. Null statuses indicate that the error is not transient. | | +| `status_code` | *Optional[str]* | :heavy_minus_sign: | The HTTP status code returned by the source platform when the error occurred. | | +| `status_text` | *Optional[str]* | :heavy_minus_sign: | A non-numeric status code/text returned by the source platform when the error occurred. | | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/dataconnectionstatus.md b/sync-for-payables/docs/models/shared/dataconnectionstatus.md index fd6fe9193..e45b6ad72 100644 --- a/sync-for-payables/docs/models/shared/dataconnectionstatus.md +++ b/sync-for-payables/docs/models/shared/dataconnectionstatus.md @@ -1,21 +1,21 @@ -# DataConnectionStatus - -The current authorization status of the data connection. - -## Example Usage - -```python -from codat_sync_for_payables.models.shared import DataConnectionStatus - -value = DataConnectionStatus.PENDING_AUTH -``` - - -## Values - -| Name | Value | -| -------------- | -------------- | -| `PENDING_AUTH` | PendingAuth | -| `LINKED` | Linked | -| `UNLINKED` | Unlinked | +# DataConnectionStatus + +The current authorization status of the data connection. + +## Example Usage + +```python +from codat_sync_for_payables.models.shared import DataConnectionStatus + +value = DataConnectionStatus.PENDING_AUTH +``` + + +## Values + +| Name | Value | +| -------------- | -------------- | +| `PENDING_AUTH` | PendingAuth | +| `LINKED` | Linked | +| `UNLINKED` | Unlinked | | `DEAUTHORIZED` | Deauthorized | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/datasetstatus.md b/sync-for-payables/docs/models/shared/datasetstatus.md new file mode 100644 index 000000000..00921648b --- /dev/null +++ b/sync-for-payables/docs/models/shared/datasetstatus.md @@ -0,0 +1,38 @@ +# DatasetStatus + +The current status of the dataset. + +## Example Usage + +```python +from codat_sync_for_payables.models.shared import DatasetStatus + +value = DatasetStatus.INITIAL +``` + + +## Values + +| Name | Value | +| ---------------------- | ---------------------- | +| `INITIAL` | Initial | +| `QUEUED` | Queued | +| `FETCHING` | Fetching | +| `MAP_QUEUED` | MapQueued | +| `MAPPING` | Mapping | +| `COMPLETE` | Complete | +| `FETCH_ERROR` | FetchError | +| `MAP_ERROR` | MapError | +| `INTERNAL_ERROR` | InternalError | +| `PROCESSING_QUEUED` | ProcessingQueued | +| `PROCESSING` | Processing | +| `PROCESSING_ERROR` | ProcessingError | +| `VALIDATION_QUEUED` | ValidationQueued | +| `VALIDATING` | Validating | +| `VALIDATION_ERROR` | ValidationError | +| `AUTH_ERROR` | AuthError | +| `CANCELLED` | Cancelled | +| `NOT_SUPPORTED` | NotSupported | +| `RATE_LIMIT_ERROR` | RateLimitError | +| `PERMISSIONS_ERROR` | PermissionsError | +| `PREREQUISITE_NOT_MET` | PrerequisiteNotMet | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/datastatus.md b/sync-for-payables/docs/models/shared/datastatus.md new file mode 100644 index 000000000..0d055c305 --- /dev/null +++ b/sync-for-payables/docs/models/shared/datastatus.md @@ -0,0 +1,14 @@ +# DataStatus + +Describes the state of data in the Codat cache for a company and data type + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `current_status` | *str* | :heavy_check_mark: | The current status of the dataset. | | +| `data_type` | *str* | :heavy_check_mark: | Available data types | invoices | +| `last_successful_sync` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `latest_successful_sync_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for the most recent successful sync of data type. | 8220fc90-55b6-47bc-9417-48ac6ea93101 | +| `latest_sync_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for most recent sync of data type. | ad474a37-2003-478e-baee-9af9f1ec2fe3 | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/datatype.md b/sync-for-payables/docs/models/shared/datatype.md index f526e4580..8b4de0bab 100644 --- a/sync-for-payables/docs/models/shared/datatype.md +++ b/sync-for-payables/docs/models/shared/datatype.md @@ -1,19 +1,19 @@ -# DataType - -The type of the linked reference. - -## Example Usage - -```python -from codat_sync_for_payables.models.shared import DataType - -value = DataType.TRACKING_CATEGORIES -``` - - -## Values - -| Name | Value | -| --------------------- | --------------------- | -| `TRACKING_CATEGORIES` | trackingCategories | -| `CUSTOMERS` | customers | \ No newline at end of file +# DataType + +Available data types + +## Example Usage + +```python +from codat_sync_for_payables.models.shared import DataType + +value = DataType.CUSTOMERS +``` + + +## Values + +| Name | Value | +| --------------------- | --------------------- | +| `CUSTOMERS` | customers | +| `TRACKING_CATEGORIES` | trackingCategories | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/datatypes.md b/sync-for-payables/docs/models/shared/datatypes.md new file mode 100644 index 000000000..3349a961b --- /dev/null +++ b/sync-for-payables/docs/models/shared/datatypes.md @@ -0,0 +1,60 @@ +# DataTypes + +Available data types + +## Example Usage + +```python +from codat_sync_for_payables.models.shared import DataTypes + +value = DataTypes.ACCOUNT_TRANSACTIONS +``` + + +## Values + +| Name | Value | +| -------------------------------- | -------------------------------- | +| `ACCOUNT_TRANSACTIONS` | accountTransactions | +| `BALANCE_SHEET` | balanceSheet | +| `BANK_ACCOUNTS` | bankAccounts | +| `BANK_TRANSACTIONS` | bankTransactions | +| `BILL_CREDIT_NOTES` | billCreditNotes | +| `BILL_PAYMENTS` | billPayments | +| `BILLS` | bills | +| `CASH_FLOW_STATEMENT` | cashFlowStatement | +| `CHART_OF_ACCOUNTS` | chartOfAccounts | +| `COMPANY` | company | +| `CREDIT_NOTES` | creditNotes | +| `CUSTOMERS` | customers | +| `DIRECT_COSTS` | directCosts | +| `DIRECT_INCOMES` | directIncomes | +| `INVOICES` | invoices | +| `ITEM_RECEIPTS` | itemReceipts | +| `ITEMS` | items | +| `JOURNAL_ENTRIES` | journalEntries | +| `JOURNALS` | journals | +| `PAYMENT_METHODS` | paymentMethods | +| `PAYMENTS` | payments | +| `PROFIT_AND_LOSS` | profitAndLoss | +| `PURCHASE_ORDERS` | purchaseOrders | +| `SALES_ORDERS` | salesOrders | +| `SUPPLIERS` | suppliers | +| `TAX_RATES` | taxRates | +| `TRACKING_CATEGORIES` | trackingCategories | +| `TRANSFERS` | transfers | +| `BANKING_ACCOUNT_BALANCES` | banking-accountBalances | +| `BANKING_ACCOUNTS` | banking-accounts | +| `BANKING_TRANSACTION_CATEGORIES` | banking-transactionCategories | +| `BANKING_TRANSACTIONS` | banking-transactions | +| `COMMERCE_COMPANY_INFO` | commerce-companyInfo | +| `COMMERCE_CUSTOMERS` | commerce-customers | +| `COMMERCE_DISPUTES` | commerce-disputes | +| `COMMERCE_LOCATIONS` | commerce-locations | +| `COMMERCE_ORDERS` | commerce-orders | +| `COMMERCE_PAYMENT_METHODS` | commerce-paymentMethods | +| `COMMERCE_PAYMENTS` | commerce-payments | +| `COMMERCE_PRODUCT_CATEGORIES` | commerce-productCategories | +| `COMMERCE_PRODUCTS` | commerce-products | +| `COMMERCE_TAX_COMPONENTS` | commerce-taxComponents | +| `COMMERCE_TRANSACTIONS` | commerce-transactions | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/errormessage.md b/sync-for-payables/docs/models/shared/errormessage.md new file mode 100644 index 000000000..425e22bbf --- /dev/null +++ b/sync-for-payables/docs/models/shared/errormessage.md @@ -0,0 +1,14 @@ +# ErrorMessage + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `can_be_retried` | *Optional[str]* | :heavy_minus_sign: | `True` if the error occurred transiently and can be retried. | +| `correlation_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier used to propagate to all downstream services and determine the source of the error. | +| `detailed_error_code` | *Optional[int]* | :heavy_minus_sign: | Machine readable error code used to automate processes based on the code returned. | +| `error` | *Optional[str]* | :heavy_minus_sign: | A brief description of the error. | +| `service` | *Optional[str]* | :heavy_minus_sign: | Codat's service the returned the error. | +| `status_code` | *Optional[int]* | :heavy_minus_sign: | The HTTP status code returned by the error. | +| `validation` | [Optional[shared.ErrorValidation]](../../models/shared/errorvalidation.md) | :heavy_minus_sign: | A human-readable object describing validation decisions Codat has made. If an operation has failed because of validation errors, they will be detailed here. | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/errorstatus.md b/sync-for-payables/docs/models/shared/errorstatus.md index 0518d7fde..23cb31423 100644 --- a/sync-for-payables/docs/models/shared/errorstatus.md +++ b/sync-for-payables/docs/models/shared/errorstatus.md @@ -1,19 +1,19 @@ -# ErrorStatus - -The current status of a transient error. Null statuses indicate that the error is not transient. - -## Example Usage - -```python -from codat_sync_for_payables.models.shared import ErrorStatus - -value = ErrorStatus.ACTIVE -``` - - -## Values - -| Name | Value | -| ---------- | ---------- | -| `ACTIVE` | Active | +# ErrorStatus + +The current status of a transient error. Null statuses indicate that the error is not transient. + +## Example Usage + +```python +from codat_sync_for_payables.models.shared import ErrorStatus + +value = ErrorStatus.ACTIVE +``` + + +## Values + +| Name | Value | +| ---------- | ---------- | +| `ACTIVE` | Active | | `RESOLVED` | Resolved | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/errorvalidation.md b/sync-for-payables/docs/models/shared/errorvalidation.md index 122badd9d..618d40ff2 100644 --- a/sync-for-payables/docs/models/shared/errorvalidation.md +++ b/sync-for-payables/docs/models/shared/errorvalidation.md @@ -1,11 +1,9 @@ -# ErrorValidation - -A human-readable object describing validation decisions Codat has made. If an operation has failed because of validation errors, they will be detailed here. - - -## Fields - -| Field | Type | Required | Description | -| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | -| `errors` | List[[shared.ErrorValidationItem](../../models/shared/errorvalidationitem.md)] | :heavy_minus_sign: | N/A | +# ErrorValidation + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | +| `errors` | List[[shared.ErrorValidationItem](../../models/shared/errorvalidationitem.md)] | :heavy_minus_sign: | N/A | | `warnings` | List[[shared.ErrorValidationItem](../../models/shared/errorvalidationitem.md)] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/errorvalidationitem.md b/sync-for-payables/docs/models/shared/errorvalidationitem.md index fca2ef14a..a2ea37332 100644 --- a/sync-for-payables/docs/models/shared/errorvalidationitem.md +++ b/sync-for-payables/docs/models/shared/errorvalidationitem.md @@ -1,10 +1,10 @@ -# ErrorValidationItem - - -## Fields - -| Field | Type | Required | Description | -| -------------------------------------------- | -------------------------------------------- | -------------------------------------------- | -------------------------------------------- | -| `item_id` | *OptionalNullable[str]* | :heavy_minus_sign: | Unique identifier for a validation item. | -| `message` | *OptionalNullable[str]* | :heavy_minus_sign: | A message outlining validation item's issue. | +# ErrorValidationItem + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------- | -------------------------------------------- | -------------------------------------------- | -------------------------------------------- | +| `item_id` | *OptionalNullable[str]* | :heavy_minus_sign: | Unique identifier for a validation item. | +| `message` | *OptionalNullable[str]* | :heavy_minus_sign: | A message outlining validation item's issue. | | `validator_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of validator. | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/halref.md b/sync-for-payables/docs/models/shared/halref.md index 94c6476ff..75aa86923 100644 --- a/sync-for-payables/docs/models/shared/halref.md +++ b/sync-for-payables/docs/models/shared/halref.md @@ -1,8 +1,8 @@ -# HalRef - - -## Fields - -| Field | Type | Required | Description | -| ------------------------ | ------------------------ | ------------------------ | ------------------------ | +# HalRef + + +## Fields + +| Field | Type | Required | Description | +| ------------------------ | ------------------------ | ------------------------ | ------------------------ | | `href` | *Optional[str]* | :heavy_minus_sign: | Uri hypertext reference. | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/links.md b/sync-for-payables/docs/models/shared/links.md index 6bbcdd92a..b91889951 100644 --- a/sync-for-payables/docs/models/shared/links.md +++ b/sync-for-payables/docs/models/shared/links.md @@ -1,11 +1,11 @@ -# Links - - -## Fields - -| Field | Type | Required | Description | -| -------------------------------------------------------- | -------------------------------------------------------- | -------------------------------------------------------- | -------------------------------------------------------- | -| `self_` | [shared.HalRef](../../models/shared/halref.md) | :heavy_check_mark: | N/A | -| `current` | [shared.HalRef](../../models/shared/halref.md) | :heavy_check_mark: | N/A | -| `next` | [Optional[shared.HalRef]](../../models/shared/halref.md) | :heavy_minus_sign: | N/A | -| `previous` | [Optional[shared.HalRef]](../../models/shared/halref.md) | :heavy_minus_sign: | N/A | \ No newline at end of file +# Links + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------- | -------------------------------------------------------- | -------------------------------------------------------- | -------------------------------------------------------- | +| `current` | [shared.HalRef](../../models/shared/halref.md) | :heavy_check_mark: | N/A | +| `next` | [Optional[shared.HalRef]](../../models/shared/halref.md) | :heavy_minus_sign: | N/A | +| `previous` | [Optional[shared.HalRef]](../../models/shared/halref.md) | :heavy_minus_sign: | N/A | +| `self_` | [shared.HalRef](../../models/shared/halref.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/pagination.md b/sync-for-payables/docs/models/shared/pagination.md index efde183b2..f551d21bc 100644 --- a/sync-for-payables/docs/models/shared/pagination.md +++ b/sync-for-payables/docs/models/shared/pagination.md @@ -1,8 +1,8 @@ -# Pagination - - -## Fields - -| Field | Type | Required | Description | -| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +# Pagination + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `continuation_token` | *Optional[str]* | :heavy_minus_sign: | A continuation token indicating there are more results to be fetched. Supply this value in the `continuationToken` query parameter in the next request to fetch the next set of results. Once no more results are available, the continuation token will not be present in the response. | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/paginginfo.md b/sync-for-payables/docs/models/shared/paginginfo.md new file mode 100644 index 000000000..b72226e79 --- /dev/null +++ b/sync-for-payables/docs/models/shared/paginginfo.md @@ -0,0 +1,11 @@ +# PagingInfo + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| `links` | [shared.Links](../../models/shared/links.md) | :heavy_check_mark: | N/A | {
"self": {
"href": "/companies"
},
"current": {
"href": "/companies?page=1\u0026pageSize=10"
}
} | +| `page_number` | *int* | :heavy_check_mark: | Current page number. | | +| `page_size` | *int* | :heavy_check_mark: | Number of items to return in results array. | | +| `total_results` | *int* | :heavy_check_mark: | Total number of items. | | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/paymentmappingoptions.md b/sync-for-payables/docs/models/shared/paymentmappingoptions.md index b8085c1e5..02b7d47ba 100644 --- a/sync-for-payables/docs/models/shared/paymentmappingoptions.md +++ b/sync-for-payables/docs/models/shared/paymentmappingoptions.md @@ -1,11 +1,11 @@ -# PaymentMappingOptions - -Gets the bill payments mapping options for a company's accounting software - - -## Fields - -| Field | Type | Required | Description | -| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -| `bank_accounts` | List[[Nullable[shared.BankAccountMappingOption]](../../models/shared/bankaccountmappingoption.md)] | :heavy_minus_sign: | N/A | +# PaymentMappingOptions + +Gets the bill payments mapping options for a company's accounting software + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | +| `bank_accounts` | List[[Nullable[shared.BankAccountMappingOption]](../../models/shared/bankaccountmappingoption.md)] | :heavy_minus_sign: | N/A | | `pagination` | [Optional[shared.Pagination]](../../models/shared/pagination.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/pulloperation.md b/sync-for-payables/docs/models/shared/pulloperation.md new file mode 100644 index 000000000..060cdccde --- /dev/null +++ b/sync-for-payables/docs/models/shared/pulloperation.md @@ -0,0 +1,22 @@ +# PullOperation + +Information about a queued, in progress or completed pull operation. +*Formally called `dataset`* + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier of the company associated to this pull operation. | 22ece347-e5f6-4896-95e0-35a4c7f17023 | +| `completed` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `connection_id` | *str* | :heavy_check_mark: | Unique identifier of the connection associated to this pull operation. | 50830828-7d39-4367-b0eb-5ddb2de5faa5 | +| `data_type` | *str* | :heavy_check_mark: | The data type you are requesting in a pull operation. | | +| `error_message` | *Optional[str]* | :heavy_minus_sign: | A message about a transient or persistent error returned by Codat or the source platform. | | +| `id` | *str* | :heavy_check_mark: | Unique identifier of the pull operation. | 943accd0-4247-42d8-865b-363c8629e1da | +| `is_completed` | *bool* | :heavy_check_mark: | `True` if the pull operation is completed successfully. The `isCompleted` property is not queryable. To filter failed pull operations, query by `status!=Complete&&status!=NotSupported` instead. | | +| `is_errored` | *bool* | :heavy_check_mark: | `True` if the pull operation entered an error state. | | +| `progress` | *int* | :heavy_check_mark: | An integer signifying the progress of the pull operation. | | +| `requested` | *str* | :heavy_check_mark: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `status` | *str* | :heavy_check_mark: | The current status of the dataset. | | +| `status_description` | *Optional[str]* | :heavy_minus_sign: | Additional information about the dataset status. | Paused until 2022-10-23T00:00:00.000Z | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/pulloperations.md b/sync-for-payables/docs/models/shared/pulloperations.md new file mode 100644 index 000000000..1c994a999 --- /dev/null +++ b/sync-for-payables/docs/models/shared/pulloperations.md @@ -0,0 +1,12 @@ +# PullOperations + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| `links` | [shared.Links](../../models/shared/links.md) | :heavy_check_mark: | N/A | {
"self": {
"href": "/companies"
},
"current": {
"href": "/companies?page=1\u0026pageSize=10"
}
} | +| `page_number` | *int* | :heavy_check_mark: | Current page number. | | +| `page_size` | *int* | :heavy_check_mark: | Number of items to return in results array. | | +| `results` | List[[shared.PullOperation](../../models/shared/pulloperation.md)] | :heavy_minus_sign: | N/A | | +| `total_results` | *int* | :heavy_check_mark: | Total number of items. | | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/pushchangetype.md b/sync-for-payables/docs/models/shared/pushchangetype.md new file mode 100644 index 000000000..5c165f123 --- /dev/null +++ b/sync-for-payables/docs/models/shared/pushchangetype.md @@ -0,0 +1,22 @@ +# PushChangeType + +Type of change being applied to record in third party platform. + +## Example Usage + +```python +from codat_sync_for_payables.models.shared import PushChangeType + +value = PushChangeType.UNKNOWN +``` + + +## Values + +| Name | Value | +| --------------------- | --------------------- | +| `UNKNOWN` | Unknown | +| `CREATED` | Created | +| `MODIFIED` | Modified | +| `DELETED` | Deleted | +| `ATTACHMENT_UPLOADED` | AttachmentUploaded | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/pushoperation.md b/sync-for-payables/docs/models/shared/pushoperation.md new file mode 100644 index 000000000..359f3d99c --- /dev/null +++ b/sync-for-payables/docs/models/shared/pushoperation.md @@ -0,0 +1,20 @@ +# PushOperation + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `changes` | List[[shared.PushOperationChange](../../models/shared/pushoperationchange.md)] | :heavy_minus_sign: | Contains a single entry that communicates which record has changed and the manner in which it changed. | | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for your SMB in Codat. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `completed_on_utc` | *Optional[str]* | :heavy_minus_sign: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `data_connection_key` | *str* | :heavy_check_mark: | Unique identifier for a company's data connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | +| `data_type` | *Optional[str]* | :heavy_minus_sign: | Available data types | invoices | +| `error_message` | *Optional[str]* | :heavy_minus_sign: | A message about the error. | | +| `push_operation_key` | *str* | :heavy_check_mark: | A unique identifier generated by Codat to represent this single push operation. This identifier can be used to track the status of the push, and should be persisted. | | +| `requested_on_utc` | *str* | :heavy_check_mark: | In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example:

```
2020-10-08T22:40:50Z
2021-01-01T00:00:00
```



When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information:

- Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z`
- Unqualified local time: `2021-11-15T01:00:00`
- UTC time offsets: `2021-11-15T01:00:00-05:00`

> Time zones
>
> Not all dates from Codat will contain information about time zones.
> Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `status` | [shared.PushOperationStatus](../../models/shared/pushoperationstatus.md) | :heavy_check_mark: | The current status of the push operation. | | +| `status_code` | *int* | :heavy_check_mark: | Push status code. | | +| `timeout_in_minutes` | *Optional[int]* | :heavy_minus_sign: | Number of minutes the push operation must complete within before it times out. | | +| ~~`timeout_in_seconds`~~ | *Optional[int]* | :heavy_minus_sign: | : warning: ** DEPRECATED **: This will be removed in a future release, please migrate away from it as soon as possible.

Number of seconds the push operation must complete within before it times out. | | +| `validation` | [Optional[shared.Validation]](../../models/shared/validation.md) | :heavy_minus_sign: | A human-readable object describing validation decisions Codat has made when pushing data into the platform. If a push has failed because of validation errors, they will be detailed here. | | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/pushoperationchange.md b/sync-for-payables/docs/models/shared/pushoperationchange.md new file mode 100644 index 000000000..aa344bfe4 --- /dev/null +++ b/sync-for-payables/docs/models/shared/pushoperationchange.md @@ -0,0 +1,10 @@ +# PushOperationChange + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | +| `attachment_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for the attachment created otherwise null. | +| `record_ref` | [Optional[shared.PushOperationRef]](../../models/shared/pushoperationref.md) | :heavy_minus_sign: | N/A | +| `type` | [Optional[shared.PushChangeType]](../../models/shared/pushchangetype.md) | :heavy_minus_sign: | Type of change being applied to record in third party platform. | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/pushoperationref.md b/sync-for-payables/docs/models/shared/pushoperationref.md new file mode 100644 index 000000000..a343c2d98 --- /dev/null +++ b/sync-for-payables/docs/models/shared/pushoperationref.md @@ -0,0 +1,10 @@ +# PushOperationRef + + +## Fields + +| Field | Type | Required | Description | +| --------------------------------------- | --------------------------------------- | --------------------------------------- | --------------------------------------- | +| `additional_properties` | Dict[str, *Any*] | :heavy_check_mark: | N/A | +| `data_type` | *Optional[str]* | :heavy_minus_sign: | Available data types | +| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for a push operation. | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/pushoperations.md b/sync-for-payables/docs/models/shared/pushoperations.md new file mode 100644 index 000000000..776ac813c --- /dev/null +++ b/sync-for-payables/docs/models/shared/pushoperations.md @@ -0,0 +1,12 @@ +# PushOperations + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| `links` | [shared.Links](../../models/shared/links.md) | :heavy_check_mark: | N/A | {
"self": {
"href": "/companies"
},
"current": {
"href": "/companies?page=1\u0026pageSize=10"
}
} | +| `page_number` | *int* | :heavy_check_mark: | Current page number. | | +| `page_size` | *int* | :heavy_check_mark: | Number of items to return in results array. | | +| `results` | List[[shared.PushOperation](../../models/shared/pushoperation.md)] | :heavy_minus_sign: | N/A | | +| `total_results` | *int* | :heavy_check_mark: | Total number of items. | | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/pushoperationstatus.md b/sync-for-payables/docs/models/shared/pushoperationstatus.md new file mode 100644 index 000000000..8817faef1 --- /dev/null +++ b/sync-for-payables/docs/models/shared/pushoperationstatus.md @@ -0,0 +1,21 @@ +# PushOperationStatus + +The current status of the push operation. + +## Example Usage + +```python +from codat_sync_for_payables.models.shared import PushOperationStatus + +value = PushOperationStatus.PENDING +``` + + +## Values + +| Name | Value | +| ----------- | ----------- | +| `PENDING` | Pending | +| `FAILED` | Failed | +| `SUCCESS` | Success | +| `TIMED_OUT` | TimedOut | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/security.md b/sync-for-payables/docs/models/shared/security.md index 2b68bd0e7..e7a8e4384 100644 --- a/sync-for-payables/docs/models/shared/security.md +++ b/sync-for-payables/docs/models/shared/security.md @@ -1,8 +1,8 @@ -# Security - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------ | ------------------------------ | ------------------------------ | ------------------------------ | ------------------------------ | -| `auth_header` | *str* | :heavy_check_mark: | N/A | Basic BASE_64_ENCODED(API_KEY) | \ No newline at end of file +# Security + + +## Fields + +| Field | Type | Required | Description | +| ------------------ | ------------------ | ------------------ | ------------------ | +| `auth_header` | *str* | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/sourcemodifieddate.md b/sync-for-payables/docs/models/shared/sourcemodifieddate.md new file mode 100644 index 000000000..17df92038 --- /dev/null +++ b/sync-for-payables/docs/models/shared/sourcemodifieddate.md @@ -0,0 +1,8 @@ +# SourceModifiedDate + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------- | +| `source_modified_date` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/sourcetype.md b/sync-for-payables/docs/models/shared/sourcetype.md index b904d62d7..227007dc0 100644 --- a/sync-for-payables/docs/models/shared/sourcetype.md +++ b/sync-for-payables/docs/models/shared/sourcetype.md @@ -1,24 +1,24 @@ -# SourceType - -The type of platform of the connection. - -## Example Usage - -```python -from codat_sync_for_payables.models.shared import SourceType - -value = SourceType.ACCOUNTING -``` - - -## Values - -| Name | Value | -| ------------ | ------------ | -| `ACCOUNTING` | Accounting | -| `BANKING` | Banking | -| `BANK_FEED` | BankFeed | -| `COMMERCE` | Commerce | -| `EXPENSE` | Expense | -| `OTHER` | Other | +# SourceType + +The type of platform of the connection. + +## Example Usage + +```python +from codat_sync_for_payables.models.shared import SourceType + +value = SourceType.ACCOUNTING +``` + + +## Values + +| Name | Value | +| ------------ | ------------ | +| `ACCOUNTING` | Accounting | +| `BANKING` | Banking | +| `BANK_FEED` | BankFeed | +| `COMMERCE` | Commerce | +| `EXPENSE` | Expense | +| `OTHER` | Other | | `UNKNOWN` | Unknown | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/status.md b/sync-for-payables/docs/models/shared/status.md new file mode 100644 index 000000000..3aa79bb5e --- /dev/null +++ b/sync-for-payables/docs/models/shared/status.md @@ -0,0 +1,36 @@ +# Status + +## Example Usage + +```python +from codat_sync_for_payables.models.shared import Status + +value = Status.INITIAL +``` + + +## Values + +| Name | Value | +| ---------------------- | ---------------------- | +| `INITIAL` | Initial | +| `QUEUED` | Queued | +| `FETCHING` | Fetching | +| `MAP_QUEUED` | MapQueued | +| `MAPPING` | Mapping | +| `COMPLETE` | Complete | +| `FETCH_ERROR` | FetchError | +| `MAP_ERROR` | MapError | +| `INTERNAL_ERROR` | InternalError | +| `PROCESSING_QUEUED` | ProcessingQueued | +| `PROCESSING` | Processing | +| `PROCESSING_ERROR` | ProcessingError | +| `VALIDATION_QUEUED` | ValidationQueued | +| `VALIDATING` | Validating | +| `VALIDATION_ERROR` | ValidationError | +| `AUTH_ERROR` | AuthError | +| `CANCELLED` | Cancelled | +| `NOT_SUPPORTED` | NotSupported | +| `RATE_LIMIT_ERROR` | RateLimitError | +| `PERMISSIONS_ERROR` | PermissionsError | +| `PREREQUISITE_NOT_MET` | PrerequisiteNotMet | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/supplier.md b/sync-for-payables/docs/models/shared/supplier.md index 3465e1473..239f39ca6 100644 --- a/sync-for-payables/docs/models/shared/supplier.md +++ b/sync-for-payables/docs/models/shared/supplier.md @@ -1,22 +1,22 @@ -# Supplier - -Suppliers are people or organizations that provide something, such as a product or service. Use the [List suppliers](https://docs.codat.io/sync-for-payables-v2-api#/operations/list-suppliers) endpoint to retrieve a list of all suppliers for a company. - -Suppliers' data links to accounts payable [bills](https://docs.codat.io/sync-for-payables-v2-api#/schemas/Bill). - - - -## Fields - -| Field | Type | Required | Description | Example | -| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -| `id` | *Optional[str]* | :heavy_minus_sign: | Identifier for the supplier, unique to the company in the accounting software. | | -| `supplier_name` | *Optional[str]* | :heavy_minus_sign: | Name of the supplier as recorded in the accounting system, typically the company name. | | -| `contact_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the main contact for the supplier. | | -| `email_address` | *OptionalNullable[str]* | :heavy_minus_sign: | Email address that the supplier may be contacted on. | | -| `phone` | *OptionalNullable[str]* | :heavy_minus_sign: | Phone number that the supplier may be contacted on. | **Example 1:** +44 25691 154789
**Example 2:** (877) 492-8687
**Example 3:** 01224 658 999 | -| `addresses` | List[[shared.Address](../../models/shared/address.md)] | :heavy_minus_sign: | An array of Addresses. | | -| `status` | [Optional[shared.SupplierStatus]](../../models/shared/supplierstatus.md) | :heavy_minus_sign: | Status of the supplier. | | -| `balance` | *OptionalNullable[Decimal]* | :heavy_minus_sign: | Amount outstanding against the supplier. | | -| `default_currency` | *OptionalNullable[str]* | :heavy_minus_sign: | Default currency the supplier's transactional data is recorded in. | | -| `source_modified_date` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | \ No newline at end of file +# Supplier + +Suppliers are people or organizations that provide something, such as a product or service. Use the [List suppliers](https://docs.codat.io/sync-for-payables-v2-api#/operations/list-suppliers) endpoint to retrieve a list of all suppliers for a company. + +Suppliers' data links to accounts payable [bills](https://docs.codat.io/sync-for-payables-v2-api#/schemas/Bill). + + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | +| `addresses` | List[[shared.Address](../../models/shared/address.md)] | :heavy_minus_sign: | An array of Addresses. | | +| `balance` | *OptionalNullable[Decimal]* | :heavy_minus_sign: | Amount outstanding against the supplier. | | +| `contact_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the main contact for the supplier. | | +| `default_currency` | *OptionalNullable[str]* | :heavy_minus_sign: | Default currency the supplier's transactional data is recorded in. | | +| `email_address` | *OptionalNullable[str]* | :heavy_minus_sign: | Email address that the supplier may be contacted on. | | +| `id` | *Optional[str]* | :heavy_minus_sign: | Identifier for the supplier, unique to the company in the accounting software. | | +| `phone` | *OptionalNullable[str]* | :heavy_minus_sign: | Phone number that the supplier may be contacted on. | **Example 1:** +44 25691 154789
**Example 2:** (877) 492-8687
**Example 3:** 01224 658 999 | +| `source_modified_date` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `status` | [Optional[shared.SupplierStatus]](../../models/shared/supplierstatus.md) | :heavy_minus_sign: | Status of the supplier. | | +| `supplier_name` | *Optional[str]* | :heavy_minus_sign: | Name of the supplier as recorded in the accounting system, typically the company name. | | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/supplierprototype.md b/sync-for-payables/docs/models/shared/supplierprototype.md index 789dcb3fa..b4ac0f70c 100644 --- a/sync-for-payables/docs/models/shared/supplierprototype.md +++ b/sync-for-payables/docs/models/shared/supplierprototype.md @@ -1,15 +1,15 @@ -# SupplierPrototype - - -## Fields - -| Field | Type | Required | Description | Example | -| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -| `supplier_name` | *str* | :heavy_check_mark: | Name of the supplier as recorded in the accounting system, typically the company name. | | -| `contact_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the main contact for the supplier. | | -| `email_address` | *OptionalNullable[str]* | :heavy_minus_sign: | Email address that the supplier may be contacted on. | | -| `phone` | *OptionalNullable[str]* | :heavy_minus_sign: | Phone number that the supplier may be contacted on. | **Example 1:** +44 25691 154789
**Example 2:** (877) 492-8687
**Example 3:** 01224 658 999 | -| `addresses` | List[[shared.Address](../../models/shared/address.md)] | :heavy_minus_sign: | An array of Addresses. | | -| `status` | [shared.SupplierStatus](../../models/shared/supplierstatus.md) | :heavy_check_mark: | Status of the supplier. | | -| `balance` | *OptionalNullable[Decimal]* | :heavy_minus_sign: | Amount outstanding against the supplier. | | -| `default_currency` | *OptionalNullable[str]* | :heavy_minus_sign: | Default currency the supplier's transactional data is recorded in. | | \ No newline at end of file +# SupplierPrototype + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | +| `addresses` | List[[shared.Address](../../models/shared/address.md)] | :heavy_minus_sign: | An array of Addresses. | | +| `balance` | *OptionalNullable[Decimal]* | :heavy_minus_sign: | Amount outstanding against the supplier. | | +| `contact_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the main contact for the supplier. | | +| `default_currency` | *OptionalNullable[str]* | :heavy_minus_sign: | Default currency the supplier's transactional data is recorded in. | | +| `email_address` | *OptionalNullable[str]* | :heavy_minus_sign: | Email address that the supplier may be contacted on. | | +| `phone` | *OptionalNullable[str]* | :heavy_minus_sign: | Phone number that the supplier may be contacted on. | **Example 1:** +44 25691 154789
**Example 2:** (877) 492-8687
**Example 3:** 01224 658 999 | +| `status` | [shared.SupplierStatus](../../models/shared/supplierstatus.md) | :heavy_check_mark: | Status of the supplier. | | +| `supplier_name` | *str* | :heavy_check_mark: | Name of the supplier as recorded in the accounting system, typically the company name. | | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/supplierref.md b/sync-for-payables/docs/models/shared/supplierref.md index 9ac54781a..4b61cbf8a 100644 --- a/sync-for-payables/docs/models/shared/supplierref.md +++ b/sync-for-payables/docs/models/shared/supplierref.md @@ -1,11 +1,9 @@ -# SupplierRef - -Reference to the supplier the record relates to. - - -## Fields - -| Field | Type | Required | Description | -| ------------------------ | ------------------------ | ------------------------ | ------------------------ | -| `id` | *str* | :heavy_check_mark: | The supplier's unique ID | +# SupplierRef + + +## Fields + +| Field | Type | Required | Description | +| ------------------------ | ------------------------ | ------------------------ | ------------------------ | +| `id` | *str* | :heavy_check_mark: | The supplier's unique ID | | `supplier_name` | *OptionalNullable[str]* | :heavy_minus_sign: | The supplier's name | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/suppliers.md b/sync-for-payables/docs/models/shared/suppliers.md index e7cd13438..b2bbadc71 100644 --- a/sync-for-payables/docs/models/shared/suppliers.md +++ b/sync-for-payables/docs/models/shared/suppliers.md @@ -1,9 +1,9 @@ -# Suppliers - - -## Fields - -| Field | Type | Required | Description | -| ---------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------- | -| `results` | List[[shared.Supplier](../../models/shared/supplier.md)] | :heavy_minus_sign: | N/A | -| `pagination` | [Optional[shared.Pagination]](../../models/shared/pagination.md) | :heavy_minus_sign: | N/A | \ No newline at end of file +# Suppliers + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------- | +| `pagination` | [Optional[shared.Pagination]](../../models/shared/pagination.md) | :heavy_minus_sign: | N/A | +| `results` | List[[shared.Supplier](../../models/shared/supplier.md)] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/supplierstatus.md b/sync-for-payables/docs/models/shared/supplierstatus.md index db5a33fb9..000eac313 100644 --- a/sync-for-payables/docs/models/shared/supplierstatus.md +++ b/sync-for-payables/docs/models/shared/supplierstatus.md @@ -1,20 +1,18 @@ -# SupplierStatus - -Status of the supplier. - -## Example Usage - -```python -from codat_sync_for_payables.models.shared import SupplierStatus - -value = SupplierStatus.UNKNOWN -``` - - -## Values - -| Name | Value | -| ---------- | ---------- | -| `UNKNOWN` | Unknown | -| `ACTIVE` | Active | +# SupplierStatus + +## Example Usage + +```python +from codat_sync_for_payables.models.shared import SupplierStatus + +value = SupplierStatus.UNKNOWN +``` + + +## Values + +| Name | Value | +| ---------- | ---------- | +| `UNKNOWN` | Unknown | +| `ACTIVE` | Active | | `ARCHIVED` | Archived | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/taxratemappingoption.md b/sync-for-payables/docs/models/shared/taxratemappingoption.md index 3d41d0365..89ae65999 100644 --- a/sync-for-payables/docs/models/shared/taxratemappingoption.md +++ b/sync-for-payables/docs/models/shared/taxratemappingoption.md @@ -1,13 +1,13 @@ -# TaxRateMappingOption - - -## Fields - -| Field | Type | Required | Description | Example | -| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `id` | *Optional[str]* | :heavy_minus_sign: | Identifier for the tax rate, unique for the company in the accounting software. | d2939064-dd3a-4c0f-9865-a238c2193515 | -| `name` | *OptionalNullable[str]* | :heavy_minus_sign: | Codat-augmented name of the tax rate in the accounting software. | | -| `code` | *OptionalNullable[str]* | :heavy_minus_sign: | Code for the tax rate from the accounting software. | | -| `effective_tax_rate` | *OptionalNullable[Decimal]* | :heavy_minus_sign: | See Effective tax rates description. | | -| `total_tax_rate` | *OptionalNullable[Decimal]* | :heavy_minus_sign: | Total (not compounded) sum of the components of a tax rate. | | -| `status` | [Optional[shared.TaxRateStatus]](../../models/shared/taxratestatus.md) | :heavy_minus_sign: | Status of the tax rate in the accounting software.
- `Active` - An active tax rate in use by a company.
- `Archived` - A tax rate that has been archived or is inactive in the accounting software. | | \ No newline at end of file +# TaxRateMappingOption + + +## Fields + +| Field | Type | Required | Description | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `code` | *OptionalNullable[str]* | :heavy_minus_sign: | Code for the tax rate from the accounting software. | +| `effective_tax_rate` | *OptionalNullable[Decimal]* | :heavy_minus_sign: | See Effective tax rates description. | +| `id` | *Optional[str]* | :heavy_minus_sign: | Identifier for the tax rate, unique for the company in the accounting software. | +| `name` | *OptionalNullable[str]* | :heavy_minus_sign: | Codat-augmented name of the tax rate in the accounting software. | +| `status` | [Optional[shared.TaxRateStatus]](../../models/shared/taxratestatus.md) | :heavy_minus_sign: | Status of the tax rate in the accounting software. - `Active` - An active tax rate in use by a company. - `Archived` - A tax rate that has been archived or is inactive in the accounting software. | +| `total_tax_rate` | *OptionalNullable[Decimal]* | :heavy_minus_sign: | Total (not compounded) sum of the components of a tax rate. | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/taxratestatus.md b/sync-for-payables/docs/models/shared/taxratestatus.md index ce18ae57c..e16e0af9a 100644 --- a/sync-for-payables/docs/models/shared/taxratestatus.md +++ b/sync-for-payables/docs/models/shared/taxratestatus.md @@ -1,21 +1,21 @@ -# TaxRateStatus - -Status of the tax rate in the accounting software. -- `Active` - An active tax rate in use by a company. -- `Archived` - A tax rate that has been archived or is inactive in the accounting software. - -## Example Usage - -```python -from codat_sync_for_payables.models.shared import TaxRateStatus - -value = TaxRateStatus.ACTIVE -``` - - -## Values - -| Name | Value | -| ---------- | ---------- | -| `ACTIVE` | Active | +# TaxRateStatus + +Status of the tax rate in the accounting software. +- `Active` - An active tax rate in use by a company. +- `Archived` - A tax rate that has been archived or is inactive in the accounting software. + +## Example Usage + +```python +from codat_sync_for_payables.models.shared import TaxRateStatus + +value = TaxRateStatus.ACTIVE +``` + + +## Values + +| Name | Value | +| ---------- | ---------- | +| `ACTIVE` | Active | | `ARCHIVED` | Archived | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/trackingref.md b/sync-for-payables/docs/models/shared/trackingref.md index dd66c6469..7bcbc688d 100644 --- a/sync-for-payables/docs/models/shared/trackingref.md +++ b/sync-for-payables/docs/models/shared/trackingref.md @@ -1,10 +1,10 @@ -# TrackingRef - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------ | -| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of the linked tracking category or the unique identifier of the linked customer. | e9a1b63d-9ff0-40e7-8038-016354b987e6 | -| `data_type` | [Optional[shared.DataType]](../../models/shared/datatype.md) | :heavy_minus_sign: | The type of the linked reference. | trackingCategories | -| `is_billable` | *Optional[bool]* | :heavy_minus_sign: | If a customer has been set as the trackingRefs.id then this boolean can be used to set whether the line item is billable to the customer or not. | | \ No newline at end of file +# TrackingRef + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------ | +| `data_type` | [Optional[shared.DataType]](../../models/shared/datatype.md) | :heavy_minus_sign: | The type of the linked reference. | +| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of the linked tracking category or the unique identifier of the linked customer. | +| `is_billable` | *Optional[bool]* | :heavy_minus_sign: | If a customer has been set as the trackingRefs.id then this boolean can be used to set whether the line item is billable to the customer or not. | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/updateconnection.md b/sync-for-payables/docs/models/shared/updateconnection.md new file mode 100644 index 000000000..439e3fee3 --- /dev/null +++ b/sync-for-payables/docs/models/shared/updateconnection.md @@ -0,0 +1,9 @@ +# UpdateConnection + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | +| `additional_properties` | Dict[str, *Any*] | :heavy_check_mark: | N/A | +| `status` | [Optional[shared.DataConnectionStatus]](../../models/shared/dataconnectionstatus.md) | :heavy_minus_sign: | The current authorization status of the data connection. | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/validation.md b/sync-for-payables/docs/models/shared/validation.md new file mode 100644 index 000000000..b208342e2 --- /dev/null +++ b/sync-for-payables/docs/models/shared/validation.md @@ -0,0 +1,11 @@ +# Validation + +A human-readable object describing validation decisions Codat has made when pushing data into the platform. If a push has failed because of validation errors, they will be detailed here. + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------- | -------------------------------------------------------------------- | +| `errors` | List[[shared.ValidationItem](../../models/shared/validationitem.md)] | :heavy_minus_sign: | N/A | +| `warnings` | List[[shared.ValidationItem](../../models/shared/validationitem.md)] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/sync-for-payables/docs/models/shared/validationitem.md b/sync-for-payables/docs/models/shared/validationitem.md new file mode 100644 index 000000000..fb2e81d98 --- /dev/null +++ b/sync-for-payables/docs/models/shared/validationitem.md @@ -0,0 +1,11 @@ +# ValidationItem + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------- | -------------------------------------------- | -------------------------------------------- | -------------------------------------------- | +| `additional_properties` | Dict[str, *Any*] | :heavy_check_mark: | N/A | +| `item_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for a validation item. | +| `message` | *Optional[str]* | :heavy_minus_sign: | A message outlining validation item's issue. | +| `validator_name` | *Optional[str]* | :heavy_minus_sign: | Name of validator. | \ No newline at end of file diff --git a/sync-for-payables/docs/models/utils/retryconfig.md b/sync-for-payables/docs/models/utils/retryconfig.md index 69dd549ec..0977111b8 100644 --- a/sync-for-payables/docs/models/utils/retryconfig.md +++ b/sync-for-payables/docs/models/utils/retryconfig.md @@ -1,24 +1,24 @@ -# RetryConfig - -Allows customizing the default retry configuration. Only usable with methods that mention they support retries. - -## Fields - -| Name | Type | Description | Example | -| ------------------------- | ----------------------------------- | --------------------------------------- | --------- | -| `strategy` | `*str*` | The retry strategy to use. | `backoff` | -| `backoff` | [BackoffStrategy](#backoffstrategy) | Configuration for the backoff strategy. | | -| `retry_connection_errors` | `*bool*` | Whether to retry on connection errors. | `true` | - -## BackoffStrategy - -The backoff strategy allows retrying a request with an exponential backoff between each retry. - -### Fields - -| Name | Type | Description | Example | -| ------------------ | --------- | ----------------------------------------- | -------- | -| `initial_interval` | `*int*` | The initial interval in milliseconds. | `500` | -| `max_interval` | `*int*` | The maximum interval in milliseconds. | `60000` | -| `exponent` | `*float*` | The exponent to use for the backoff. | `1.5` | +# RetryConfig + +Allows customizing the default retry configuration. Only usable with methods that mention they support retries. + +## Fields + +| Name | Type | Description | Example | +| ------------------------- | ----------------------------------- | --------------------------------------- | --------- | +| `strategy` | `*str*` | The retry strategy to use. | `backoff` | +| `backoff` | [BackoffStrategy](#backoffstrategy) | Configuration for the backoff strategy. | | +| `retry_connection_errors` | `*bool*` | Whether to retry on connection errors. | `true` | + +## BackoffStrategy + +The backoff strategy allows retrying a request with an exponential backoff between each retry. + +### Fields + +| Name | Type | Description | Example | +| ------------------ | --------- | ----------------------------------------- | -------- | +| `initial_interval` | `*int*` | The initial interval in milliseconds. | `500` | +| `max_interval` | `*int*` | The maximum interval in milliseconds. | `60000` | +| `exponent` | `*float*` | The exponent to use for the backoff. | `1.5` | | `max_elapsed_time` | `*int*` | The maximum elapsed time in milliseconds. | `300000` | \ No newline at end of file diff --git a/sync-for-payables/docs/sdks/bankaccounts/README.md b/sync-for-payables/docs/sdks/bankaccounts/README.md index 6e6cbfda6..6f6e20f09 100644 --- a/sync-for-payables/docs/sdks/bankaccounts/README.md +++ b/sync-for-payables/docs/sdks/bankaccounts/README.md @@ -1,124 +1,118 @@ -# BankAccounts - -## Overview - -Create a bank account for a given company's connection. - -### Available Operations - -* [create](#create) - Create bank account - -## create - -The *Create bank account* endpoint creates a new [bank account](https://docs.codat.io/sync-for-payables-api#/schemas/BankAccount) for a given company's connection. - -[Bank accounts](https://docs.codat.io/sync-for-payables-api#/schemas/BankAccount) are financial accounts maintained by a bank or other financial institution. - -### Example Usage: Bank account example - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.bank_accounts.create(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "bank_account_prototype": { - "nominal_code": "22", - "name": "Plutus - Payables - Bank Account 12", - "account_type": shared.BankAccountType.DEBIT, - "account_number": "0120 0440", - "sort_code": "50-50-50", - "currency": "GBP", - }, - }) - - # Handle response - print(res) - -``` -### Example Usage: Created bank account - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.bank_accounts.create(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "bank_account_prototype": { - "name": "", - "account_type": shared.BankAccountType.DEBIT, - "account_number": "", - "currency": "GBP", - }, - }) - - # Handle response - print(res) - -``` -### Example Usage: Malformed query - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.bank_accounts.create(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "bank_account_prototype": { - "name": "", - "account_type": shared.BankAccountType.DEBIT, - "account_number": "", - "currency": "GBP", - }, - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | -| `request` | [operations.CreateBankAccountRequest](../../models/operations/createbankaccountrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.BankAccount](../../models/shared/bankaccount.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ---------------------------- | ---------------------------- | ---------------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | +# BankAccounts + +## Overview + +Create a bank account for a given company's connection. + +### Available Operations + +* [create](#create) - Create bank account + +## create + +The *Create bank account* endpoint creates a new [bank account](https://docs.codat.io/sync-for-payables-api#/schemas/BankAccount) for a given company's connection. + +[Bank accounts](https://docs.codat.io/sync-for-payables-api#/schemas/BankAccount) are financial accounts maintained by a bank or other financial institution. + +### Example Usage: Bank account example + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.bank_accounts.create(request={ + "bank_account_prototype": { + "account_number": "0120 0440", + "account_type": shared.BankAccountType.DEBIT, + "currency": "GBP", + "name": "Plutus - Payables - Bank Account 12", + "nominal_code": "22", + "sort_code": "50-50-50", + }, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` +### Example Usage: Created bank account + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.bank_accounts.create(request={ + "bank_account_prototype": { + "currency": "GBP", + }, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` +### Example Usage: Malformed query + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.bank_accounts.create(request={ + "bank_account_prototype": { + "currency": "GBP", + }, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | +| `request` | [operations.CreateBankAccountRequest](../../models/operations/createbankaccountrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.BankAccount](../../models/shared/bankaccount.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ---------------------------- | ---------------------------- | ---------------------------- | +| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | | errors.SDKError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/sync-for-payables/docs/sdks/billpayments/README.md b/sync-for-payables/docs/sdks/billpayments/README.md index f047b0862..8d6373f1c 100644 --- a/sync-for-payables/docs/sdks/billpayments/README.md +++ b/sync-for-payables/docs/sdks/billpayments/README.md @@ -1,189 +1,183 @@ -# BillPayments - -## Overview - -Get, create, and update Bill payments. - -### Available Operations - -* [get_payment_options](#get_payment_options) - Get payment mapping options -* [create](#create) - Create bill payment - -## get_payment_options - -Use the *Get mapping options - Payments* endpoint to return a list of available mapping options for a given company's connection ID. - -By default, this endpoint returns a list of active bank accounts. You can use [querying](https://docs.codat.io/using-the-api/querying) to change that. - -Mapping options are a set of bank accounts used to configure the SMB's payables integration. - -### Example Usage - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.bill_payments.get_payment_options(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "continuation_token": "continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ==", - "status_query": "status=Archived", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | -| `request` | [operations.GetMappingOptionsPaymentsRequest](../../models/operations/getmappingoptionspaymentsrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.PaymentMappingOptions](../../models/shared/paymentmappingoptions.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ---------------------------- | ---------------------------- | ---------------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## create - -The *Create bill payment* endpoint creates a new [bill payment](https://docs.codat.io/sync-for-payables-api#/schemas/BillPayment) for a given company's connection. - -[Bill payments](https://docs.codat.io/sync-for-payables-api#/schemas/BillPayment) are an allocation of money within any Accounts Payable account. - -### Example Usage: Bill payment - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared -from decimal import Decimal - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.bill_payments.create(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "bill_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - "bill_payment_prototype": { - "amount": Decimal("1329.54"), - "date_": "2022-10-23T00:00:00Z", - "reference": "Bill Payment against bill c13e37b6-dfaa-4894-b3be-9fe97bda9f44", - "account_ref": { - "id": "", - }, - }, - }) - - # Handle response - print(res) - -``` -### Example Usage: Bill payment example - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared -from decimal import Decimal - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.bill_payments.create(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "bill_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - "bill_payment_prototype": { - "amount": Decimal("22"), - "date_": "2022-10-23T00:00:00.000Z", - "reference": "Bill Payment against bill c13e37b6 dfaa-4894-b3be-9fe97bda9f44", - "account_ref": { - "id": "7bda9f44sr56", - }, - "currency_rate": Decimal("1"), - }, - }) - - # Handle response - print(res) - -``` -### Example Usage: Malformed query - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared -from decimal import Decimal - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.bill_payments.create(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "bill_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - "bill_payment_prototype": { - "amount": Decimal("1329.54"), - "date_": "2022-10-23T00:00:00Z", - "reference": "Bill Payment against bill c13e37b6-dfaa-4894-b3be-9fe97bda9f44", - "account_ref": { - "id": "", - }, - }, - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | -| `request` | [operations.CreateBillPaymentRequest](../../models/operations/createbillpaymentrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.BillPayment](../../models/shared/billpayment.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| --------------------------------- | --------------------------------- | --------------------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 404, 409, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | +# BillPayments + +## Overview + +Get, create, and update Bill payments. + +### Available Operations + +* [get_payment_options](#get_payment_options) - Get payment mapping options +* [create](#create) - Create bill payment + +## get_payment_options + +Use the *Get mapping options - Payments* endpoint to return a list of available mapping options for a given company's connection ID. + +By default, this endpoint returns a list of active bank accounts. You can use [querying](https://docs.codat.io/using-the-api/querying) to change that. + +Mapping options are a set of bank accounts used to configure the SMB's payables integration. + +### Example Usage + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.bill_payments.get_payment_options(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + "continuation_token": "continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ==", + "status_query": "status=Archived", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | +| `request` | [operations.GetMappingOptionsPaymentsRequest](../../models/operations/getmappingoptionspaymentsrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.PaymentMappingOptions](../../models/shared/paymentmappingoptions.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ---------------------------- | ---------------------------- | ---------------------------- | +| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## create + +The *Create bill payment* endpoint creates a new [bill payment](https://docs.codat.io/sync-for-payables-api#/schemas/BillPayment) for a given company's connection. + +[Bill payments](https://docs.codat.io/sync-for-payables-api#/schemas/BillPayment) are an allocation of money within any Accounts Payable account. + +### Example Usage: Bill payment + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared +from decimal import Decimal + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.bill_payments.create(request={ + "bill_payment_prototype": { + "amount": Decimal("1329.54"), + "date_": "2022-10-23T00:00:00Z", + "reference": "Bill Payment against bill c13e37b6-dfaa-4894-b3be-9fe97bda9f44", + }, + "bill_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` +### Example Usage: Bill payment example + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared +from decimal import Decimal + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.bill_payments.create(request={ + "bill_payment_prototype": { + "account_ref": { + "id": "7bda9f44sr56", + }, + "amount": Decimal("22"), + "currency_rate": Decimal("1"), + "date_": "2022-10-23T00:00:00.000Z", + "reference": "Bill Payment against bill c13e37b6 dfaa-4894-b3be-9fe97bda9f44", + }, + "bill_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` +### Example Usage: Malformed query + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared +from decimal import Decimal + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.bill_payments.create(request={ + "bill_payment_prototype": { + "amount": Decimal("1329.54"), + "date_": "2022-10-23T00:00:00Z", + "reference": "Bill Payment against bill c13e37b6-dfaa-4894-b3be-9fe97bda9f44", + }, + "bill_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | +| `request` | [operations.CreateBillPaymentRequest](../../models/operations/createbillpaymentrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.BillPayment](../../models/shared/billpayment.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| --------------------------------- | --------------------------------- | --------------------------------- | +| errors.ErrorMessage | 400, 401, 402, 403, 404, 409, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | | errors.SDKError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/sync-for-payables/docs/sdks/bills/README.md b/sync-for-payables/docs/sdks/bills/README.md index 2e234e1bf..3828d69fc 100644 --- a/sync-for-payables/docs/sdks/bills/README.md +++ b/sync-for-payables/docs/sdks/bills/README.md @@ -1,774 +1,653 @@ -# Bills - -## Overview - -Get, create, and update Bills. - -### Available Operations - -* [get_bill_options](#get_bill_options) - Get bill mapping options -* [list](#list) - List bills -* [create](#create) - Create bill -* [update](#update) - Update bill -* [upload_attachment](#upload_attachment) - Upload bill attachment -* [list_attachments](#list_attachments) - List bill attachments -* [download_attachment](#download_attachment) - Download bill attachment - -## get_bill_options - -Use the *Get mapping options - Bills* endpoint to return a list of available mapping options for a given company's connection ID. - -By default, this endpoint returns a list of active accounts and tax rates. You can use [querying](https://docs.codat.io/using-the-api/querying) to change that. - -Mapping options are a set of accounts and tax rates used to configure the SMB's payables integration. - -### Example Usage - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.bills.get_bill_options(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "continuation_token": "continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ==", - "status_query": "status=Archived", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | -| `request` | [operations.GetMappingOptionsBillsRequest](../../models/operations/getmappingoptionsbillsrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.BillMappingOptions](../../models/shared/billmappingoptions.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ---------------------------- | ---------------------------- | ---------------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## list - -The *List bills* endpoint returns a list of [bills](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) for a given company's connection. - -[Bills](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) are invoices that represent the SMB's financial obligations to their supplier for a purchase of goods or services. - -By default, the endpoint will return all bills with a status of 'Open' & 'PartiallyPaid' to show all oustanding bills. - -### Example Usage: Bills - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.bills.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "continuation_token": "continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ==", - }) - - # Handle response - print(res) - -``` -### Example Usage: Source modified date - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.bills.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "continuation_token": "continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ==", - "query": "sourceModifiedDate>2023-12-15T00:00:00.000Z", - }) - - # Handle response - print(res) - -``` -### Example Usage: Status (open) - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.bills.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "continuation_token": "continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ==", - "query": "status=Open", - }) - - # Handle response - print(res) - -``` -### Example Usage: Status (open) & source modified date - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.bills.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "continuation_token": "continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ==", - "query": "sourceModifiedDate>2023-12-15T00:00:00.000Z&&status=Open", - }) - - # Handle response - print(res) - -``` -### Example Usage: Status (partially paid) - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.bills.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "continuation_token": "continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ==", - "query": "status=PartiallyPaid", - }) - - # Handle response - print(res) - -``` -### Example Usage: Status (partially paid) & source modified date - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.bills.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "continuation_token": "continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ==", - "query": "sourceModifiedDate>2023-12-15T00:00:00.000Z&&status=PartiallyPaid", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| -------------------------------------------------------------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------------- | -| `request` | [operations.ListBillsRequest](../../models/operations/listbillsrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.Bills](../../models/shared/bills.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| --------------------------------- | --------------------------------- | --------------------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 404, 409, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## create - -The *Create bill* endpoint creates a new [bill](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) for a given company's connection. - -[Bills](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) are invoices that represent the SMB's financial obligations to their supplier for a purchase of goods or services. - -### Example Usage: Create bill - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared -from decimal import Decimal - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.bills.create(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "bill_prototype": { - "reference": "bill_b8qmmj4ksf1suax", - "supplier_ref": { - "id": "1262c350-fe0f-40ec-aeff-41c95b4a45af", - "supplier_name": "DIISR - Small Business Services", - }, - "issue_date": "2023-04-23T00:00:00", - "due_date": "2023-04-23T00:00:00", - "currency": "GBP", - "currency_rate": Decimal("1"), - "line_items": [ - { - "description": "Half day training - Microsoft Office", - "unit_amount": Decimal("1800"), - "quantity": Decimal("1"), - "tax_amount": Decimal("360"), - "account_ref": { - "id": "46f9461e-788b-4906-8b74-d1ea17f6dc10", - }, - "total_amount": Decimal("2160"), - "tax_rate_ref": { - "id": "INPUT2", - }, - }, - { - "description": "Desktop/network support via email & phone.Per month fixed fee for minimum 20 hours/month.", - "unit_amount": Decimal("4000"), - "quantity": Decimal("1"), - "tax_amount": Decimal("800"), - "account_ref": { - "id": "f96c9458-d724-47bf-8f74-a9d5726465ce", - }, - "total_amount": Decimal("4800"), - "tax_rate_ref": { - "id": "INPUT2", - }, - }, - { - "description": "Stationery charges", - "unit_amount": Decimal("32"), - "quantity": Decimal("8"), - "tax_amount": Decimal("51.2"), - "account_ref": { - "id": "cba6527d-f102-4538-b421-e483233e9d5a", - }, - "total_amount": Decimal("307.2"), - "tax_rate_ref": { - "id": "INPUT2", - }, - "tracking_refs": [ - { - "id": "dba3d4da-f9ed-4eee-8e0b-452d11fdb1fa", - "data_type": shared.DataType.TRACKING_CATEGORIES, - }, - ], - }, - ], - "status": shared.BillStatus.OPEN, - }, - }) - - # Handle response - print(res) - -``` -### Example Usage: Created bill - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.bills.create(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "bill_prototype": { - "supplier_ref": { - "id": "", - }, - "issue_date": "2022-10-23T00:00:00Z", - "due_date": "2022-10-23T00:00:00Z", - "currency": "GBP", - "line_items": [ - { - "tracking_refs": None, - }, - ], - "status": shared.BillStatus.OPEN, - }, - }) - - # Handle response - print(res) - -``` -### Example Usage: Malformed query - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.bills.create(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "bill_prototype": { - "supplier_ref": { - "id": "", - }, - "issue_date": "2022-10-23T00:00:00Z", - "due_date": "2022-10-23T00:00:00Z", - "currency": "GBP", - "line_items": [ - { - "tracking_refs": None, - }, - ], - "status": shared.BillStatus.OPEN, - }, - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | -| `request` | [operations.CreateBillRequest](../../models/operations/createbillrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.Bill](../../models/shared/bill.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| --------------------------------- | --------------------------------- | --------------------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 404, 409, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## update - -The *Update bill* endpoint updates an existing [bill](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) for a given company's connection. - -[Bills](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) are invoices that represent the SMB's financial obligations to their supplier for a purchase of goods or services. - -### Supported Integrations - -| Integration | Supported | -|-------------------------------|-----------| -| FreeAgent | Yes | -| QuickBooks Online | Yes | -| Xero | Yes | -| Oracle NetSuite | No | -| Sage Intacct | No | -| Zoho Books | No | - - -### Example Usage: Malformed query - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.bills.update(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "bill_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - "bill_prototype": { - "supplier_ref": { - "id": "", - }, - "issue_date": "2022-10-23T00:00:00Z", - "due_date": "2022-10-23T00:00:00Z", - "currency": "GBP", - "line_items": [ - { - "tracking_refs": [ - { - "id": "e9a1b63d-9ff0-40e7-8038-016354b987e6", - "data_type": shared.DataType.TRACKING_CATEGORIES, - }, - ], - }, - ], - "status": shared.BillStatus.OPEN, - }, - }) - - # Handle response - print(res) - -``` -### Example Usage: Update bill - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared -from decimal import Decimal - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.bills.update(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "bill_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - "bill_prototype": { - "reference": "bill_updated_ref", - "supplier_ref": { - "id": "1262c350-fe0f-40ec-aeff-41c95b4a45af", - }, - "issue_date": "2023-04-23T00:00:00", - "due_date": "2023-05-23T00:00:00", - "currency": "GBP", - "currency_rate": Decimal("1"), - "line_items": [ - { - "description": "Updated line item - Microsoft Office training", - "unit_amount": Decimal("2000"), - "quantity": Decimal("1"), - "tax_amount": Decimal("400"), - "account_ref": { - "id": "46f9461e-788b-4906-8b74-d1ea17f6dc10", - }, - "total_amount": Decimal("2400"), - "tax_rate_ref": { - "id": "INPUT2", - }, - }, - { - "description": "Desktop/network support via email & phone - updated rate", - "unit_amount": Decimal("4500"), - "quantity": Decimal("1"), - "tax_amount": Decimal("900"), - "account_ref": { - "id": "f96c9458-d724-47bf-8f74-a9d5726465ce", - }, - "total_amount": Decimal("5400"), - "tax_rate_ref": { - "id": "INPUT2", - }, - "tracking_refs": [ - { - "id": "dba3d4da-f9ed-4eee-8e0b-452d11fdb1fa", - "data_type": shared.DataType.TRACKING_CATEGORIES, - }, - ], - }, - ], - "status": shared.BillStatus.OPEN, - }, - }) - - # Handle response - print(res) - -``` -### Example Usage: Updated bill - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.bills.update(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "bill_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - "bill_prototype": { - "supplier_ref": { - "id": "", - }, - "issue_date": "2022-10-23T00:00:00Z", - "due_date": "2022-10-23T00:00:00Z", - "currency": "GBP", - "line_items": [ - { - "tracking_refs": [ - { - "id": "e9a1b63d-9ff0-40e7-8038-016354b987e6", - "data_type": shared.DataType.TRACKING_CATEGORIES, - }, - ], - }, - ], - "status": shared.BillStatus.OPEN, - }, - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | -| `request` | [operations.UpdateBillRequest](../../models/operations/updatebillrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.Bill](../../models/shared/bill.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| --------------------------------- | --------------------------------- | --------------------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 404, 409, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## upload_attachment - -The *Upload bill attachment* endpoint uploads an attachment and assigns it against a specific `billId`. - -[Bills](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) are invoices that represent the SMB's financial obligations to their supplier for a purchase of goods or services. - -### Example Usage - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.bills.upload_attachment(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "bill_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | -| `request` | [operations.UploadBillAttachmentRequest](../../models/operations/uploadbillattachmentrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.Attachment](../../models/shared/attachment.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ---------------------------- | ---------------------------- | ---------------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## list_attachments - -The *List bill attachments* endpoint returns a list of attachments available to download for a given `billId`. - -[Bills](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) are invoices that represent the SMB's financial obligations to their supplier for a purchase of goods or services. - -### Example Usage - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.bills.list_attachments(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "bill_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | -| `request` | [operations.ListBillAttachmentsRequest](../../models/operations/listbillattachmentsrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[List[shared.Attachment]](../../models/.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ---------------------------- | ---------------------------- | ---------------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 409, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## download_attachment - -The *Download bill attachment* endpoint downloads a specific attachment for a given `billId` and `attachmentId`. - -[Bills](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) are invoices that represent the SMB's financial obligations to their supplier for a purchase of goods or services. - - -### Example Usage - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.bills.download_attachment(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "bill_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - "attachment_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | -| `request` | [operations.DownloadBillAttachmentRequest](../../models/operations/downloadbillattachmentrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[httpx.Response](../../models/data.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | +# Bills + +## Overview + +Get, create, and update Bills. + +### Available Operations + +* [get_bill_options](#get_bill_options) - Get bill mapping options +* [list](#list) - List bills +* [create](#create) - Create bill +* [update](#update) - Update bill +* [upload_attachment](#upload_attachment) - Upload bill attachment +* [list_attachments](#list_attachments) - List bill attachments +* [download_attachment](#download_attachment) - Download bill attachment + +## get_bill_options + +Use the *Get mapping options - Bills* endpoint to return a list of available mapping options for a given company's connection ID. + +By default, this endpoint returns a list of active accounts and tax rates. You can use [querying](https://docs.codat.io/using-the-api/querying) to change that. + +Mapping options are a set of accounts and tax rates used to configure the SMB's payables integration. + +### Example Usage + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.bills.get_bill_options(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + "continuation_token": "continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ==", + "status_query": "status=Archived", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | +| `request` | [operations.GetMappingOptionsBillsRequest](../../models/operations/getmappingoptionsbillsrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.BillMappingOptions](../../models/shared/billmappingoptions.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ---------------------------- | ---------------------------- | ---------------------------- | +| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## list + +The *List bills* endpoint returns a list of [bills](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) for a given company's connection. + +[Bills](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) are invoices that represent the SMB's financial obligations to their supplier for a purchase of goods or services. + +By default, the endpoint will return all bills with a status of 'Open' & 'PartiallyPaid' to show all oustanding bills. + +### Example Usage: Bills + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.bills.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + "continuation_token": "continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ==", + }) + + # Handle response + print(res) + +``` +### Example Usage: Source modified date + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.bills.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + "continuation_token": "continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ==", + "query": "sourceModifiedDate>2023-12-15T00:00:00.000Z", + }) + + # Handle response + print(res) + +``` +### Example Usage: Status (open) + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.bills.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + "continuation_token": "continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ==", + "query": "status=Open", + }) + + # Handle response + print(res) + +``` +### Example Usage: Status (open) & source modified date + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.bills.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + "continuation_token": "continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ==", + "query": "sourceModifiedDate>2023-12-15T00:00:00.000Z&&status=Open", + }) + + # Handle response + print(res) + +``` +### Example Usage: Status (partially paid) + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.bills.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + "continuation_token": "continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ==", + "query": "status=PartiallyPaid", + }) + + # Handle response + print(res) + +``` +### Example Usage: Status (partially paid) & source modified date + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.bills.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + "continuation_token": "continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ==", + "query": "sourceModifiedDate>2023-12-15T00:00:00.000Z&&status=PartiallyPaid", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| -------------------------------------------------------------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------------- | +| `request` | [operations.ListBillsRequest](../../models/operations/listbillsrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.Bills](../../models/shared/bills.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| --------------------------------- | --------------------------------- | --------------------------------- | +| errors.ErrorMessage | 400, 401, 402, 403, 404, 409, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## create + +The *Create bill* endpoint creates a new [bill](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) for a given company's connection. + +[Bills](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) are invoices that represent the SMB's financial obligations to their supplier for a purchase of goods or services. + +### Example Usage: Create bill + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared +from decimal import Decimal + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.bills.create(request={ + "bill_prototype": { + "currency": "GBP", + "currency_rate": Decimal("1"), + "due_date": "2023-04-23T00:00:00", + "issue_date": "2023-04-23T00:00:00", + "line_items": [], + "reference": "bill_b8qmmj4ksf1suax", + "status": shared.BillStatus.OPEN, + "supplier_ref": { + "id": "1262c350-fe0f-40ec-aeff-41c95b4a45af", + "supplier_name": "DIISR - Small Business Services", + }, + }, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` +### Example Usage: Created bill + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.bills.create(request={ + "bill_prototype": { + "currency": "GBP", + "due_date": "2022-10-23T00:00:00Z", + "issue_date": "2022-10-23T00:00:00Z", + "status": shared.BillStatus.OPEN, + }, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` +### Example Usage: Malformed query + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.bills.create(request={ + "bill_prototype": { + "currency": "GBP", + "due_date": "2022-10-23T00:00:00Z", + "issue_date": "2022-10-23T00:00:00Z", + "status": shared.BillStatus.OPEN, + }, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | +| `request` | [operations.CreateBillRequest](../../models/operations/createbillrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.Bill](../../models/shared/bill.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| --------------------------------- | --------------------------------- | --------------------------------- | +| errors.ErrorMessage | 400, 401, 402, 403, 404, 409, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## update + +The *Update bill* endpoint updates an existing [bill](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) for a given company's connection. + +[Bills](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) are invoices that represent the SMB's financial obligations to their supplier for a purchase of goods or services. + +### Supported Integrations + +| Integration | Supported | +|-------------------------------|-----------| +| FreeAgent | Yes | +| QuickBooks Online | Yes | +| Xero | Yes | +| Oracle NetSuite | No | +| Sage Intacct | No | +| Zoho Books | No | + + +### Example Usage: Malformed query + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.bills.update(request={ + "bill_prototype": { + "currency": "GBP", + "due_date": "2022-10-23T00:00:00Z", + "issue_date": "2022-10-23T00:00:00Z", + "status": shared.BillStatus.OPEN, + }, + "bill_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` +### Example Usage: Update bill + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared +from decimal import Decimal + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.bills.update(request={ + "bill_prototype": { + "currency": "GBP", + "currency_rate": Decimal("1"), + "due_date": "2023-05-23T00:00:00", + "issue_date": "2023-04-23T00:00:00", + "line_items": [], + "reference": "bill_updated_ref", + "status": shared.BillStatus.OPEN, + "supplier_ref": { + "id": "1262c350-fe0f-40ec-aeff-41c95b4a45af", + }, + }, + "bill_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` +### Example Usage: Updated bill + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.bills.update(request={ + "bill_prototype": { + "currency": "GBP", + "due_date": "2022-10-23T00:00:00Z", + "issue_date": "2022-10-23T00:00:00Z", + "status": shared.BillStatus.OPEN, + }, + "bill_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | +| `request` | [operations.UpdateBillRequest](../../models/operations/updatebillrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.Bill](../../models/shared/bill.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| --------------------------------- | --------------------------------- | --------------------------------- | +| errors.ErrorMessage | 400, 401, 402, 403, 404, 409, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## upload_attachment + +The *Upload bill attachment* endpoint uploads an attachment and assigns it against a specific `billId`. + +[Bills](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) are invoices that represent the SMB's financial obligations to their supplier for a purchase of goods or services. + +### Example Usage + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.bills.upload_attachment(request={ + "bill_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | +| `request` | [operations.UploadBillAttachmentRequest](../../models/operations/uploadbillattachmentrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.Attachment](../../models/shared/attachment.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ---------------------------- | ---------------------------- | ---------------------------- | +| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## list_attachments + +The *List bill attachments* endpoint returns a list of attachments available to download for a given `billId`. + +[Bills](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) are invoices that represent the SMB's financial obligations to their supplier for a purchase of goods or services. + +### Example Usage + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.bills.list_attachments(request={ + "bill_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | +| `request` | [operations.ListBillAttachmentsRequest](../../models/operations/listbillattachmentsrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[List[shared.Attachment]](../../models/.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ---------------------------- | ---------------------------- | ---------------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 409, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## download_attachment + +The *Download bill attachment* endpoint downloads a specific attachment for a given `billId` and `attachmentId`. + +[Bills](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) are invoices that represent the SMB's financial obligations to their supplier for a purchase of goods or services. + + +### Example Usage + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.bills.download_attachment(request={ + "attachment_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "bill_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | +| `request` | [operations.DownloadBillAttachmentRequest](../../models/operations/downloadbillattachmentrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[httpx.Response](../../models/data.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | | errors.SDKError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/sync-for-payables/docs/sdks/companies/README.md b/sync-for-payables/docs/sdks/companies/README.md index 11511bc79..d56168d87 100644 --- a/sync-for-payables/docs/sdks/companies/README.md +++ b/sync-for-payables/docs/sdks/companies/README.md @@ -1,571 +1,567 @@ -# Companies - -## Overview - -Create and manage your SMB users' companies. - -### Available Operations - -* [list](#list) - List companies -* [create](#create) - Create company -* [replace](#replace) - Replace company -* [update](#update) - Update company -* [delete](#delete) - Delete a company -* [get](#get) - Get company - -## list - -The *List companies* endpoint returns a list of [companies](https://docs.codat.io/sync-for-payables-api#/schemas/Company) associated to your instances. - -A [company](https://docs.codat.io/sync-for-payables-api#/schemas/Company) represents a business sharing access to their data. -Each company can have multiple [connections](https://docs.codat.io/sync-for-payables-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. - -## Filter by tags - -The *List companies* endpoint supports the filtering of companies using [tags](https://docs.codat.io/using-the-api/managing-companies#add-metadata-to-a-company). It supports the following operators with [Codat’s query language](https://docs.codat.io/using-the-api/querying): - -- equals (`=`) -- not equals (`!=`) -- contains (`~`) - -For example, you can use the querying to filter companies tagged with a specific foreign key, region, or owning team: -- Foreign key: `uid = {yourCustomerId}` -- Region: `region != uk` -- Owning team and region: `region = uk && owningTeam = invoice-finance` - -### Example Usage: List of Companies - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.companies.list(request={ - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - "order_by": "-modifiedDate", - "tags": "region=uk && team=invoice-finance", - }) - - # Handle response - print(res) - -``` -### Example Usage: One company - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.companies.list(request={ - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - "order_by": "-modifiedDate", - "tags": "region=uk && team=invoice-finance", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | -| `request` | [operations.ListCompaniesRequest](../../models/operations/listcompaniesrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.Companies](../../models/shared/companies.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ---------------------------- | ---------------------------- | ---------------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## create - -Use the *Create company* endpoint to create a new [company](https://docs.codat.io/sync-for-payables-api#/schemas/Company) that represents your customer in Codat. - -A [company](https://docs.codat.io/sync-for-payables-api#/schemas/Company) represents a business sharing access to their data. -Each company can have multiple [connections](https://docs.codat.io/sync-for-payables-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. - -If forbidden characters (see `name` pattern) are present in the request, a company will be created with the forbidden characters removed. For example, `Company (Codat[1])` with be created as `Company Codat1`. - -### Example Usage: Malformed query - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.companies.create(request={ - "name": "Bank of Dave", - "description": "Requested early access to the new financing scheme.", - }) - - # Handle response - print(res) - -``` -### Example Usage: With a description - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.companies.create(request={ - "name": "Technicalium", - "description": "Technology services, including web and app design and development", - }) - - # Handle response - print(res) - -``` -### Example Usage: With a tag - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.companies.create(request={ - "name": "Bank of Dave", - "description": "Requested early access to the new financing scheme.", - }) - - # Handle response - print(res) - -``` -### Example Usage: With no description - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.companies.create(request={ - "name": "Technicalium", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | -| `request` | [shared.CompanyRequestBody](../../models/shared/companyrequestbody.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.Company](../../models/shared/company.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## replace - -Use the *Replace company* endpoint to replace the existing name, description, and tags of the company. Calling the endpoint will replace existing values even if new values haven't been defined in the payload. - -A [company](https://docs.codat.io/sync-for-payables-api#/schemas/Company) represents a business sharing access to their data. -Each company can have multiple [connections](https://docs.codat.io/sync-for-payables-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. - -### Example Usage: Unauthorized - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.companies.replace(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "company_request_body": { - "name": "Bank of Dave", - "description": "Requested early access to the new financing scheme.", - }, - }) - - # Handle response - print(res) - -``` -### Example Usage: Update description - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.companies.replace(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "company_request_body": { - "name": "Same name", - "description": "Additional documents required", - }, - }) - - # Handle response - print(res) - -``` -### Example Usage: Update name - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.companies.replace(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "company_request_body": { - "name": "New Name", - }, - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | -| `request` | [operations.ReplaceCompanyRequest](../../models/operations/replacecompanyrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.Company](../../models/shared/company.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## update - -Use the *Update company* endpoint to update the name, description, or tags of the company. - -The *Update company* endpoint doesn't have any required fields. If any of the fields provided are `null` or not provided, they won't be included in the update. - -A [company](https://docs.codat.io/sync-for-payables-api#/schemas/Company) represents a business sharing access to their data. - -### Example Usage: Unauthorized - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.companies.update(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "company_update_request": { - "name": "Bank of Dave", - "description": "Requested early access to the new financing scheme.", - }, - }) - - # Handle response - print(res) - -``` -### Example Usage: Update name - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.companies.update(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "company_update_request": { - "name": "New Name", - }, - }) - - # Handle response - print(res) - -``` -### Example Usage: Update tags - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.companies.update(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "company_update_request": { - "tags": { - "refrence": "new reference", - }, - }, - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | -| `request` | [operations.UpdateCompanyRequest](../../models/operations/updatecompanyrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.Company](../../models/shared/company.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## delete - -The *Delete company* endpoint permanently deletes a [company](https://docs.codat.io/sync-for-payables-api#/schemas/Company), its [connections](https://docs.codat.io/sync-for-payables-api#/schemas/Connection) and any cached data. This operation is irreversible. - -A [company](https://docs.codat.io/sync-for-payables-api#/schemas/Company) represents a business sharing access to their data. -Each company can have multiple [connections](https://docs.codat.io/sync-for-payables-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. - - -### Example Usage - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - codat_sync_payables.companies.delete(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Use the SDK ... - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | -| `request` | [operations.DeleteCompanyRequest](../../models/operations/deletecompanyrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## get - -The *Get company* endpoint returns a single company for a given `companyId`. - -A [company](https://docs.codat.io/sync-for-payables-api#/schemas/Company) represents a business sharing access to their data. -Each company can have multiple [connections](https://docs.codat.io/sync-for-payables-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. - - -### Example Usage: Parent multi-entity company - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.companies.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` -### Example Usage: Simple company - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.companies.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` -### Example Usage: Subsidiary multi-entity company - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.companies.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | -| `request` | [operations.GetCompanyRequest](../../models/operations/getcompanyrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.Company](../../models/shared/company.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | +# Companies + +## Overview + +Create and manage your SMB users' companies. + +### Available Operations + +* [list](#list) - List companies +* [create](#create) - Create company +* [replace](#replace) - Replace company +* [update](#update) - Update company +* [delete](#delete) - Delete a company +* [get](#get) - Get company + +## list + +The *List companies* endpoint returns a list of [companies](https://docs.codat.io/sync-for-payables-api#/schemas/Company) associated to your instances. + +A [company](https://docs.codat.io/sync-for-payables-api#/schemas/Company) represents a business sharing access to their data. +Each company can have multiple [connections](https://docs.codat.io/sync-for-payables-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. + +## Filter by tags + +The *List companies* endpoint supports the filtering of companies using [tags](https://docs.codat.io/using-the-api/managing-companies#add-metadata-to-a-company). It supports the following operators with [Codat’s query language](https://docs.codat.io/using-the-api/querying): + +- equals (`=`) +- not equals (`!=`) +- contains (`~`) + +For example, you can use the querying to filter companies tagged with a specific foreign key, region, or owning team: +- Foreign key: `uid = {yourCustomerId}` +- Region: `region != uk` +- Owning team and region: `region = uk && owningTeam = invoice-finance` + +### Example Usage: List of Companies + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.companies.list(request={ + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + "tags": "region=uk && team=invoice-finance", + }) + + # Handle response + print(res) + +``` +### Example Usage: One company + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.companies.list(request={ + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + "tags": "region=uk && team=invoice-finance", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | +| `request` | [operations.ListCompaniesRequest](../../models/operations/listcompaniesrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.Companies](../../models/shared/companies.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ---------------------------- | ---------------------------- | ---------------------------- | +| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## create + +Use the *Create company* endpoint to create a new [company](https://docs.codat.io/sync-for-payables-api#/schemas/Company) that represents your customer in Codat. + +A [company](https://docs.codat.io/sync-for-payables-api#/schemas/Company) represents a business sharing access to their data. +Each company can have multiple [connections](https://docs.codat.io/sync-for-payables-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. + +If forbidden characters (see `name` pattern) are present in the request, a company will be created with the forbidden characters removed. For example, `Company (Codat[1])` with be created as `Company Codat1`. + +### Example Usage: Malformed query + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.companies.create(request={ + "description": "Requested early access to the new financing scheme.", + "name": "Bank of Dave", + }) + + # Handle response + print(res) + +``` +### Example Usage: With a description + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.companies.create(request={ + "description": "Technology services, including web and app design and development", + "name": "Technicalium", + }) + + # Handle response + print(res) + +``` +### Example Usage: With a tag + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.companies.create(request={ + "description": "Requested early access to the new financing scheme.", + "name": "Bank of Dave", + }) + + # Handle response + print(res) + +``` +### Example Usage: With no description + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.companies.create(request={ + "name": "Technicalium", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | +| `request` | [shared.CompanyRequestBody](../../models/shared/companyrequestbody.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.Company](../../models/shared/company.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 400, 401, 402, 403, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## replace + +Use the *Replace company* endpoint to replace the existing name, description, and tags of the company. Calling the endpoint will replace existing values even if new values haven't been defined in the payload. + +A [company](https://docs.codat.io/sync-for-payables-api#/schemas/Company) represents a business sharing access to their data. +Each company can have multiple [connections](https://docs.codat.io/sync-for-payables-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. + +### Example Usage: Unauthorized + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.companies.replace(request={ + "company_request_body": { + "description": "Requested early access to the new financing scheme.", + "name": "Bank of Dave", + }, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` +### Example Usage: Update description + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.companies.replace(request={ + "company_request_body": { + "description": "Additional documents required", + "name": "Same name", + }, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` +### Example Usage: Update name + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.companies.replace(request={ + "company_request_body": { + "name": "New Name", + }, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | +| `request` | [operations.ReplaceCompanyRequest](../../models/operations/replacecompanyrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.Company](../../models/shared/company.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## update + +Use the *Update company* endpoint to update the name, description, or tags of the company. + +The *Update company* endpoint doesn't have any required fields. If any of the fields provided are `null` or not provided, they won't be included in the update. + +A [company](https://docs.codat.io/sync-for-payables-api#/schemas/Company) represents a business sharing access to their data. + +### Example Usage: Unauthorized + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.companies.update(request={ + "company_update_request": { + "description": "Requested early access to the new financing scheme.", + "name": "Bank of Dave", + }, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` +### Example Usage: Update name + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.companies.update(request={ + "company_update_request": { + "name": "New Name", + }, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` +### Example Usage: Update tags + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.companies.update(request={ + "company_update_request": {}, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | +| `request` | [operations.UpdateCompanyRequest](../../models/operations/updatecompanyrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.Company](../../models/shared/company.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## delete + +The *Delete company* endpoint permanently deletes a [company](https://docs.codat.io/sync-for-payables-api#/schemas/Company), its [connections](https://docs.codat.io/sync-for-payables-api#/schemas/Connection) and any cached data. This operation is irreversible. + +A [company](https://docs.codat.io/sync-for-payables-api#/schemas/Company) represents a business sharing access to their data. +Each company can have multiple [connections](https://docs.codat.io/sync-for-payables-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. + + +### Example Usage + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + codat_sync_payables.companies.delete(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Use the SDK ... + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | +| `request` | [operations.DeleteCompanyRequest](../../models/operations/deletecompanyrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## get + +The *Get company* endpoint returns a single company for a given `companyId`. + +A [company](https://docs.codat.io/sync-for-payables-api#/schemas/Company) represents a business sharing access to their data. +Each company can have multiple [connections](https://docs.codat.io/sync-for-payables-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. + + +### Example Usage: Parent multi-entity company + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.companies.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` +### Example Usage: Simple company + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.companies.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` +### Example Usage: Subsidiary multi-entity company + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.companies.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | +| `request` | [operations.GetCompanyRequest](../../models/operations/getcompanyrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.Company](../../models/shared/company.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | | errors.SDKError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/sync-for-payables/docs/sdks/companyinformation/README.md b/sync-for-payables/docs/sdks/companyinformation/README.md index 80ce6cb10..c2ecb9768 100644 --- a/sync-for-payables/docs/sdks/companyinformation/README.md +++ b/sync-for-payables/docs/sdks/companyinformation/README.md @@ -1,58 +1,58 @@ -# CompanyInformation - -## Overview - -View company profile from the source platform. - -### Available Operations - -* [get](#get) - Get company information - -## get - -Use the *Get company information* endpoint to return information about the company available from the underlying accounting software. - - - -### Example Usage - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.company_information.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -| `request` | [operations.GetCompanyInformationRequest](../../models/operations/getcompanyinformationrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.CompanyInformation](../../models/shared/companyinformation.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ---------------------------- | ---------------------------- | ---------------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | +# CompanyInformation + +## Overview + +View company profile from the source platform. + +### Available Operations + +* [get](#get) - Get company information + +## get + +Use the *Get company information* endpoint to return information about the company available from the underlying accounting software. + + + +### Example Usage + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.company_information.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | +| `request` | [operations.GetCompanyInformationRequest](../../models/operations/getcompanyinformationrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.CompanyInformation](../../models/shared/companyinformation.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ---------------------------- | ---------------------------- | ---------------------------- | +| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | | errors.SDKError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/sync-for-payables/docs/sdks/connections/README.md b/sync-for-payables/docs/sdks/connections/README.md index 9dce0e2b9..1d618cea5 100644 --- a/sync-for-payables/docs/sdks/connections/README.md +++ b/sync-for-payables/docs/sdks/connections/README.md @@ -1,277 +1,271 @@ -# Connections - -## Overview - -Create new and manage existing data connections for a company. - -### Available Operations - -* [list](#list) - List connections -* [create](#create) - Create connection -* [get](#get) - Get connection -* [delete](#delete) - Delete connection -* [unlink](#unlink) - Unlink connection - -## list - -List the connections for a company. - -### Example Usage - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.connections.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - "order_by": "-modifiedDate", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -| `request` | [operations.ListConnectionsRequest](../../models/operations/listconnectionsrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.Connections](../../models/shared/connections.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ---------------------------- | ---------------------------- | ---------------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## create - -Creates a connection for the company by providing a valid `platformKey`. - -Use the [List Integrations](https://docs.codat.io/platform-api#/operations/list-integrations) endpoint to access valid platform keys. - -### Example Usage: Connection - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.connections.create(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "request_body": { - "platform_key": "gbol", - }, - }) - - # Handle response - print(res) - -``` -### Example Usage: Unauthorized - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.connections.create(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "request_body": { - "platform_key": "gbol", - }, - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | -| `request` | [operations.CreateConnectionRequest](../../models/operations/createconnectionrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.Connection](../../models/shared/connection.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## get - -Returns a specific connection for a company when valid identifiers are provided. If the identifiers are for a deleted company and/or connection, a not found response is returned. - -### Example Usage - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.connections.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | -| `request` | [operations.GetConnectionRequest](../../models/operations/getconnectionrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.Connection](../../models/shared/connection.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## delete - -Revoke and remove a connection from a company. -This operation is not reversible. The end user would need to reauthorize a new data connection if you wish to view new data for this company. - -### Example Usage - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - codat_sync_payables.connections.delete(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - }) - - # Use the SDK ... - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | -| `request` | [operations.DeleteConnectionRequest](../../models/operations/deleteconnectionrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## unlink - -This allows you to deauthorize a connection, without deleting it from Codat. This means you can still view any data that has previously been pulled into Codat, and also lets you re-authorize in future if your customer wishes to resume sharing their data. - -### Example Usage - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.connections.unlink(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "request_body": { - "status": shared.DataConnectionStatus.UNLINKED, - }, - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | -| `request` | [operations.UnlinkConnectionRequest](../../models/operations/unlinkconnectionrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.Connection](../../models/shared/connection.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | +# Connections + +## Overview + +Create new and manage existing data connections for a company. + +### Available Operations + +* [list](#list) - List connections +* [create](#create) - Create connection +* [get](#get) - Get connection +* [delete](#delete) - Delete connection +* [unlink](#unlink) - Unlink connection + +## list + +List the connections for a company. + +### Example Usage + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.connections.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | +| `request` | [operations.ListConnectionsRequest](../../models/operations/listconnectionsrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.Connections](../../models/shared/connections.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ---------------------------- | ---------------------------- | ---------------------------- | +| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## create + +Creates a connection for the company by providing a valid `platformKey`. + +Use the [List Integrations](https://docs.codat.io/platform-api#/operations/list-integrations) endpoint to access valid platform keys. + +### Example Usage: Connection + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.connections.create(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` +### Example Usage: Unauthorized + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.connections.create(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| `request` | [operations.CreateConnectionRequest](../../models/operations/createconnectionrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.Connection](../../models/shared/connection.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## get + +Returns a specific connection for a company when valid identifiers are provided. If the identifiers are for a deleted company and/or connection, a not found response is returned. + +### Example Usage + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.connections.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | +| `request` | [operations.GetConnectionRequest](../../models/operations/getconnectionrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.Connection](../../models/shared/connection.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## delete + +Revoke and remove a connection from a company. +This operation is not reversible. The end user would need to reauthorize a new data connection if you wish to view new data for this company. + +### Example Usage + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + codat_sync_payables.connections.delete(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Use the SDK ... + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| `request` | [operations.DeleteConnectionRequest](../../models/operations/deleteconnectionrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## unlink + +This allows you to deauthorize a connection, without deleting it from Codat. This means you can still view any data that has previously been pulled into Codat, and also lets you re-authorize in future if your customer wishes to resume sharing their data. + +### Example Usage + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.connections.unlink(request={ + "request_body": { + "status": shared.DataConnectionStatus.UNLINKED, + }, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| `request` | [operations.UnlinkConnectionRequest](../../models/operations/unlinkconnectionrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.Connection](../../models/shared/connection.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------- | ----------------------- | ----------------------- | +| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | | errors.SDKError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/sync-for-payables/docs/sdks/suppliers/README.md b/sync-for-payables/docs/sdks/suppliers/README.md index 051ccf6a7..49fbfe0f0 100644 --- a/sync-for-payables/docs/sdks/suppliers/README.md +++ b/sync-for-payables/docs/sdks/suppliers/README.md @@ -1,455 +1,429 @@ -# Suppliers - -## Overview - -Get, create, and update Suppliers. - -### Available Operations - -* [list](#list) - List suppliers -* [create](#create) - Create supplier -* [update](#update) - Update supplier - -## list - -The *List suppliers* endpoint returns a list of [suppliers](https://docs.codat.io/sync-for-payables-api#/schemas/Supplier) for a given company's connection. - -[Suppliers](https://docs.codat.io/sync-for-payables-api#/schemas/Supplier) are people or organizations that provide something, such as a product or service. - -By default, this endpoint returns a list of active and archived suppliers. You can use [querying](https://docs.codat.io/using-the-api/querying) to change that. - -For example, to retrieve only active suppliers (i.e. `status=Active`) or suppliers created within the specified number of days (e.g. `sourceModifiedDate>2023-12-15T00:00:00.000Z`), query the endpoint as follows: `/payables/suppliers?query=sourceModifiedDate>2023-12-15T00:00:00.000Z&&status=Active`.For example, to retrieve active suppliers modified after a particular date use `query=sourceModifiedDate>2023-12-15T00:00:00.000Z&&status=Active`. - -### Supported Integrations - -| Integration | Supported | -|-------------------------------|-----------| -| FreeAgent | Yes | -| QuickBooks Online | Yes | -| Xero | Yes | -| Oracle NetSuite | Yes | -| Sage Intacct | Yes | -| Zoho Books | Yes | - -### Example Usage: Source modified date - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.suppliers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "continuation_token": "continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ==", - "query": "sourceModifiedDate>2023-12-15T00:00:00.000Z", - }) - - # Handle response - print(res) - -``` -### Example Usage: Status (active) - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.suppliers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "continuation_token": "continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ==", - "query": "status=Active", - }) - - # Handle response - print(res) - -``` -### Example Usage: Status (active) & source modified date - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.suppliers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "continuation_token": "continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ==", - "query": "sourceModifiedDate>2023-12-15T00:00:00.000Z&&status=Active", - }) - - # Handle response - print(res) - -``` -### Example Usage: Status (archived) - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.suppliers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "continuation_token": "continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ==", - "query": "status=Archived", - }) - - # Handle response - print(res) - -``` -### Example Usage: Status (archived) & source modified date - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.suppliers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "continuation_token": "continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ==", - "query": "sourceModifiedDate>2023-12-15T00:00:00.000Z&&status=Archived", - }) - - # Handle response - print(res) - -``` -### Example Usage: Suppliers - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.suppliers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "continuation_token": "continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ==", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | -| `request` | [operations.ListSuppliersRequest](../../models/operations/listsuppliersrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.Suppliers](../../models/shared/suppliers.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| --------------------------------- | --------------------------------- | --------------------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 404, 409, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## create - -The *Create supplier* endpoint creates a new [supplier](https://docs.codat.io/sync-for-payables-api#/schemas/Supplier) for a given company's connection. - -[Suppliers](https://docs.codat.io/sync-for-payables-api#/schemas/Supplier) are people or organizations that provide something, such as a product or service. - -### Supported Integrations - -| Integration | Supported | -|-------------------------------|-----------| -| FreeAgent | Yes | -| QuickBooks Online | Yes | -| Xero | Yes | -| Oracle NetSuite | Yes | -| Sage Intacct | Yes | -| Zoho Books | Yes | - - -### Example Usage: Malformed query - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.suppliers.create(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "supplier_prototype": { - "supplier_name": "", - "phone": "+44 25691 154789", - "status": shared.SupplierStatus.UNKNOWN, - }, - }) - - # Handle response - print(res) - -``` -### Example Usage: Suppliers - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.suppliers.create(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "supplier_prototype": { - "supplier_name": "Northridge Office Supplies", - "contact_name": "Sarah Johnson", - "email_address": "sarah.johnson@northridgesupplies.co.uk", - "phone": "+44 (0)1223 322410", - "addresses": [ - { - "type": shared.AddressType.BILLING, - "line1": "Flat 1", - "line2": "2 Dennis Avenue", - "city": "London", - "region": "Camden", - "country": "GB", - "postal_code": "EC1N 7TE", - }, - ], - "status": shared.SupplierStatus.ACTIVE, - "default_currency": "GBP", - }, - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | -| `request` | [operations.CreateSupplierRequest](../../models/operations/createsupplierrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.Supplier](../../models/shared/supplier.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ---------------------------- | ---------------------------- | ---------------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## update - -The *Update supplier* endpoint updates an existing [supplier](https://docs.codat.io/sync-for-payables-api#/schemas/Supplier) for a given company's connection. - -[Suppliers](https://docs.codat.io/sync-for-payables-api#/schemas/Supplier) are people or organizations that provide something, such as a product or service. - -This is a full-replace PUT endpoint. Any fields not included in the request body will be cleared on the supplier record. - -### Supported Integrations - -| Integration | Supported | -|-------------------------------|-----------| -| FreeAgent | Yes | -| QuickBooks Online | Yes | -| Xero | Yes | -| Oracle NetSuite | No | -| Sage Intacct | No | -| Zoho Books | No | - -### Platform-specific behavior - -- **Xero**: Archived suppliers cannot be updated (returns `400`). Suppliers must be unarchived manually in the Xero UI before updating. -- **QuickBooks Online**: Currency can only be set when creating a supplier, and cannot be changed via update. - - -### Example Usage: Malformed query - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.suppliers.update(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - "supplier_prototype": { - "supplier_name": "", - "phone": "+44 25691 154789", - "status": shared.SupplierStatus.ACTIVE, - }, - }) - - # Handle response - print(res) - -``` -### Example Usage: Update supplier - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.suppliers.update(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - "supplier_prototype": { - "supplier_name": "Northridge Office Supplies", - "contact_name": "Sarah Johnson", - "email_address": "sarah.johnson@northridgesupplies.co.uk", - "phone": "+44 (0)1223 322410", - "addresses": [ - { - "type": shared.AddressType.BILLING, - "line1": "Flat 1", - "line2": "2 Dennis Avenue", - "city": "London", - "region": "Camden", - "country": "GB", - "postal_code": "EC1N 7TE", - }, - ], - "status": shared.SupplierStatus.ACTIVE, - "default_currency": "GBP", - }, - }) - - # Handle response - print(res) - -``` -### Example Usage: Updated supplier - - -```python -from codat_sync_for_payables import CodatSyncPayables -from codat_sync_for_payables.models import shared - - -with CodatSyncPayables( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_payables: - - res = codat_sync_payables.suppliers.update(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - "supplier_prototype": { - "supplier_name": "", - "phone": "+44 25691 154789", - "status": shared.SupplierStatus.ACTIVE, - }, - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | -| `request` | [operations.UpdateSupplierRequest](../../models/operations/updatesupplierrequest.md) | :heavy_check_mark: | The request object to use for the request. | -| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | - -### Response - -**[shared.Supplier](../../models/shared/supplier.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ---------------------------- | ---------------------------- | ---------------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | +# Suppliers + +## Overview + +Get, create, and update Suppliers. + +### Available Operations + +* [list](#list) - List suppliers +* [create](#create) - Create supplier +* [update](#update) - Update supplier + +## list + +The *List suppliers* endpoint returns a list of [suppliers](https://docs.codat.io/sync-for-payables-api#/schemas/Supplier) for a given company's connection. + +[Suppliers](https://docs.codat.io/sync-for-payables-api#/schemas/Supplier) are people or organizations that provide something, such as a product or service. + +By default, this endpoint returns a list of active and archived suppliers. You can use [querying](https://docs.codat.io/using-the-api/querying) to change that. + +For example, to retrieve only active suppliers (i.e. `status=Active`) or suppliers created within the specified number of days (e.g. `sourceModifiedDate>2023-12-15T00:00:00.000Z`), query the endpoint as follows: `/payables/suppliers?query=sourceModifiedDate>2023-12-15T00:00:00.000Z&&status=Active`.For example, to retrieve active suppliers modified after a particular date use `query=sourceModifiedDate>2023-12-15T00:00:00.000Z&&status=Active`. + +### Supported Integrations + +| Integration | Supported | +|-------------------------------|-----------| +| FreeAgent | Yes | +| QuickBooks Online | Yes | +| Xero | Yes | +| Oracle NetSuite | Yes | +| Sage Intacct | Yes | +| Zoho Books | Yes | + +### Example Usage: Source modified date + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.suppliers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + "continuation_token": "continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ==", + "query": "sourceModifiedDate>2023-12-15T00:00:00.000Z", + }) + + # Handle response + print(res) + +``` +### Example Usage: Status (active) + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.suppliers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + "continuation_token": "continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ==", + "query": "status=Active", + }) + + # Handle response + print(res) + +``` +### Example Usage: Status (active) & source modified date + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.suppliers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + "continuation_token": "continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ==", + "query": "sourceModifiedDate>2023-12-15T00:00:00.000Z&&status=Active", + }) + + # Handle response + print(res) + +``` +### Example Usage: Status (archived) + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.suppliers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + "continuation_token": "continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ==", + "query": "status=Archived", + }) + + # Handle response + print(res) + +``` +### Example Usage: Status (archived) & source modified date + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.suppliers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + "continuation_token": "continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ==", + "query": "sourceModifiedDate>2023-12-15T00:00:00.000Z&&status=Archived", + }) + + # Handle response + print(res) + +``` +### Example Usage: Suppliers + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.suppliers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + "continuation_token": "continuationToken=eyJwYWdlIjoyLCJwYWdlU2l6ZSI6MTAwLCJwYWdlQ291bnQiOjExfQ==", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | +| `request` | [operations.ListSuppliersRequest](../../models/operations/listsuppliersrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.Suppliers](../../models/shared/suppliers.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| --------------------------------- | --------------------------------- | --------------------------------- | +| errors.ErrorMessage | 400, 401, 402, 403, 404, 409, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## create + +The *Create supplier* endpoint creates a new [supplier](https://docs.codat.io/sync-for-payables-api#/schemas/Supplier) for a given company's connection. + +[Suppliers](https://docs.codat.io/sync-for-payables-api#/schemas/Supplier) are people or organizations that provide something, such as a product or service. + +### Supported Integrations + +| Integration | Supported | +|-------------------------------|-----------| +| FreeAgent | Yes | +| QuickBooks Online | Yes | +| Xero | Yes | +| Oracle NetSuite | Yes | +| Sage Intacct | Yes | +| Zoho Books | Yes | + + +### Example Usage: Malformed query + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.suppliers.create(request={ + "supplier_prototype": { + "phone": "+44 25691 154789", + }, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` +### Example Usage: Suppliers + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.suppliers.create(request={ + "supplier_prototype": { + "addresses": [], + "contact_name": "Sarah Johnson", + "default_currency": "GBP", + "email_address": "sarah.johnson@northridgesupplies.co.uk", + "phone": "+44 (0)1223 322410", + "status": shared.SupplierStatus.ACTIVE, + "supplier_name": "Northridge Office Supplies", + }, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | +| `request` | [operations.CreateSupplierRequest](../../models/operations/createsupplierrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.Supplier](../../models/shared/supplier.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ---------------------------- | ---------------------------- | ---------------------------- | +| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## update + +The *Update supplier* endpoint updates an existing [supplier](https://docs.codat.io/sync-for-payables-api#/schemas/Supplier) for a given company's connection. + +[Suppliers](https://docs.codat.io/sync-for-payables-api#/schemas/Supplier) are people or organizations that provide something, such as a product or service. + +This is a full-replace PUT endpoint. Any fields not included in the request body will be cleared on the supplier record. + +### Supported Integrations + +| Integration | Supported | +|-------------------------------|-----------| +| FreeAgent | Yes | +| QuickBooks Online | Yes | +| Xero | Yes | +| Oracle NetSuite | No | +| Sage Intacct | No | +| Zoho Books | No | + +### Platform-specific behavior + +- **Xero**: Archived suppliers cannot be updated (returns `400`). Suppliers must be unarchived manually in the Xero UI before updating. +- **QuickBooks Online**: Currency can only be set when creating a supplier, and cannot be changed via update. + + +### Example Usage: Malformed query + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.suppliers.update(request={ + "supplier_prototype": { + "phone": "+44 25691 154789", + }, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: Update supplier + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.suppliers.update(request={ + "supplier_prototype": { + "addresses": [], + "contact_name": "Sarah Johnson", + "default_currency": "GBP", + "email_address": "sarah.johnson@northridgesupplies.co.uk", + "phone": "+44 (0)1223 322410", + "status": shared.SupplierStatus.ACTIVE, + "supplier_name": "Northridge Office Supplies", + }, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: Updated supplier + + +```python +from codat_sync_for_payables import CodatSyncPayables +from codat_sync_for_payables.models import shared + + +with CodatSyncPayables( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_payables: + + res = codat_sync_payables.suppliers.update(request={ + "supplier_prototype": { + "phone": "+44 25691 154789", + }, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | +| `request` | [operations.UpdateSupplierRequest](../../models/operations/updatesupplierrequest.md) | :heavy_check_mark: | The request object to use for the request. | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | + +### Response + +**[shared.Supplier](../../models/shared/supplier.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| ---------------------------- | ---------------------------- | ---------------------------- | +| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | | errors.SDKError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/sync-for-payables/pyproject.toml b/sync-for-payables/pyproject.toml index a597b20e8..11491f406 100644 --- a/sync-for-payables/pyproject.toml +++ b/sync-for-payables/pyproject.toml @@ -1,58 +1,35 @@ - [project] name = "codat-sync-for-payables" -version = "9.1.0" +version = "9.1.1" description = "Streamline your customers' accounts payable workflow." -authors = [{ name = "Speakeasy" },] +authors = [{ name = "Codat", email = "support@codat.io" }] readme = "README-PYPI.md" -requires-python = ">=3.10" +requires-python = ">=3.8" dependencies = [ - "httpcore >=1.0.9", - "httpx >=0.28.1", - "pydantic >=2.11.2", + "urllib3 >= 1.25.3, < 3.0.0", + "python-dateutil >= 2.8.2", + "pydantic >= 2", + "typing-extensions >= 4.7.1", + "httpx >= 0.28.1", + "httpcore >= 1.0.9", ] +[project.urls] +Repository = "https://github.com/codatio/client-sdk-python.git" + [tool.poetry] -repository = "https://github.com/codatio/client-sdk-python.git" packages = [ - { include = "codat_sync_for_payables", from = "src" } + { include = "codat_sync_for_payables", from = "src" }, ] -include = ["py.typed", "src/codat_sync_for_payables/py.typed"] - -[tool.setuptools.package-data] -"*" = ["py.typed", "src/codat_sync_for_payables/py.typed"] - -[virtualenvs] -in-project = true +include = ["src/codat_sync_for_payables/py.typed"] [tool.poetry.group.dev.dependencies] -mypy = "==1.15.0" -pylint = "==3.2.3" -pyright = "==1.1.398" +pytest = ">=7.2.1" +mypy = ">=1.5" [build-system] requires = ["poetry-core"] build-backend = "poetry.core.masonry.api" [tool.pytest.ini_options] -asyncio_default_fixture_loop_scope = "function" pythonpath = ["src"] - -[tool.mypy] -disable_error_code = "misc" -explicit_package_bases = true -mypy_path = "src" - -[[tool.mypy.overrides]] -module = "typing_inspect" -ignore_missing_imports = true - -[[tool.mypy.overrides]] -module = "jsonpath" -ignore_missing_imports = true - -[tool.pyright] -venvPath = "." -venv = ".venv" - - diff --git a/sync-for-payables/src/codat_sync_for_payables/__init__.py b/sync-for-payables/src/codat_sync_for_payables/__init__.py index 833c68cd5..e55c7f199 100644 --- a/sync-for-payables/src/codat_sync_for_payables/__init__.py +++ b/sync-for-payables/src/codat_sync_for_payables/__init__.py @@ -1,4 +1,112 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +# flake8: noqa + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +__version__ = "1.0.0" + +# import apis into sdk package +from codat_sync_for_payables.api.bank_accounts import BankAccounts +from codat_sync_for_payables.api.bill_payments import BillPayments +from codat_sync_for_payables.api.bills import Bills +from codat_sync_for_payables.api.companies import Companies +from codat_sync_for_payables.api.company_information import CompanyInformation +from codat_sync_for_payables.api.connections import Connections +from codat_sync_for_payables.api.suppliers import Suppliers + +# import ApiClient +from codat_sync_for_payables.api_response import ApiResponse +from codat_sync_for_payables.api_client import ApiClient +from codat_sync_for_payables.configuration import Configuration +from codat_sync_for_payables.exceptions import OpenApiException +from codat_sync_for_payables.exceptions import ApiTypeError +from codat_sync_for_payables.exceptions import ApiValueError +from codat_sync_for_payables.exceptions import ApiKeyError +from codat_sync_for_payables.exceptions import ApiAttributeError +from codat_sync_for_payables.exceptions import ApiException + +# import models into sdk package +from codat_sync_for_payables.models.shared.accountmappingoption import AccountMappingOption +from codat_sync_for_payables.models.shared.accountstatus import AccountStatus +from codat_sync_for_payables.models.shared.address import Address +from codat_sync_for_payables.models.shared.addresstype import AddressType +from codat_sync_for_payables.models.shared.attachment import Attachment +from codat_sync_for_payables.models.shared.bankaccount import BankAccount +from codat_sync_for_payables.models.shared.bankaccountmappingoption import BankAccountMappingOption +from codat_sync_for_payables.models.shared.bankaccountprototype import BankAccountPrototype +from codat_sync_for_payables.models.shared.bankaccountstatus import BankAccountStatus +from codat_sync_for_payables.models.shared.bankaccounttype import BankAccountType +from codat_sync_for_payables.models.shared.bill import Bill +from codat_sync_for_payables.models.shared.billaccountref import BillAccountRef +from codat_sync_for_payables.models.bill_event_payload import BillEventPayload +from codat_sync_for_payables.models.bill_event_webhook import BillEventWebhook +from codat_sync_for_payables.models.shared.billlineitem import BillLineItem +from codat_sync_for_payables.models.shared.billmappingoptions import BillMappingOptions +from codat_sync_for_payables.models.shared.billpayment import BillPayment +from codat_sync_for_payables.models.shared.billpaymentaccountref import BillPaymentAccountRef +from codat_sync_for_payables.models.shared.billpaymentprototype import BillPaymentPrototype +from codat_sync_for_payables.models.shared.billprototype import BillPrototype +from codat_sync_for_payables.models.shared.billstatus import BillStatus +from codat_sync_for_payables.models.shared.billtaxrateref import BillTaxRateRef +from codat_sync_for_payables.models.shared.bills import Bills +from codat_sync_for_payables.models.shared.clientratelimitwebhook import ClientRateLimitWebhook +from codat_sync_for_payables.models.shared.clientratelimitwebhookpayload import ClientRateLimitWebhookPayload +from codat_sync_for_payables.models.shared.companies import Companies +from codat_sync_for_payables.models.shared.company import Company +from codat_sync_for_payables.models.company_details import CompanyDetails +from codat_sync_for_payables.models.shared.companyinformation import CompanyInformation +from codat_sync_for_payables.models.shared.companyreference import CompanyReference +from codat_sync_for_payables.models.company_reference_links import CompanyReferenceLinks +from codat_sync_for_payables.models.shared.companyrequestbody import CompanyRequestBody +from codat_sync_for_payables.models.shared.companyupdaterequest import CompanyUpdateRequest +from codat_sync_for_payables.models.shared.connection import Connection +from codat_sync_for_payables.models.shared.connections import Connections +from codat_sync_for_payables.models.create_connection_request import CreateConnectionRequest +from codat_sync_for_payables.models.shared.dataconnectionerror import DataConnectionError +from codat_sync_for_payables.models.shared.dataconnectionstatus import DataConnectionStatus +from codat_sync_for_payables.models.data_status import DataStatus +from codat_sync_for_payables.models.data_type import DataType +from codat_sync_for_payables.models.error_message import ErrorMessage +from codat_sync_for_payables.models.shared.errorvalidation import ErrorValidation +from codat_sync_for_payables.models.shared.errorvalidationitem import ErrorValidationItem +from codat_sync_for_payables.models.shared.halref import HalRef +from codat_sync_for_payables.models.shared.links import Links +from codat_sync_for_payables.models.shared.pagination import Pagination +from codat_sync_for_payables.models.paging_info import PagingInfo +from codat_sync_for_payables.models.shared.paymentmappingoptions import PaymentMappingOptions +from codat_sync_for_payables.models.pull_operation import PullOperation +from codat_sync_for_payables.models.pull_operations import PullOperations +from codat_sync_for_payables.models.push_change_type import PushChangeType +from codat_sync_for_payables.models.push_operation import PushOperation +from codat_sync_for_payables.models.push_operation_change import PushOperationChange +from codat_sync_for_payables.models.push_operation_ref import PushOperationRef +from codat_sync_for_payables.models.push_operation_status import PushOperationStatus +from codat_sync_for_payables.models.push_operations import PushOperations +from codat_sync_for_payables.models.source_modified_date import SourceModifiedDate +from codat_sync_for_payables.models.status import Status +from codat_sync_for_payables.models.shared.supplier import Supplier +from codat_sync_for_payables.models.shared.supplierprototype import SupplierPrototype +from codat_sync_for_payables.models.shared.supplierref import SupplierRef +from codat_sync_for_payables.models.shared.supplierstatus import SupplierStatus +from codat_sync_for_payables.models.shared.suppliers import Suppliers +from codat_sync_for_payables.models.shared.taxratemappingoption import TaxRateMappingOption +from codat_sync_for_payables.models.shared.trackingref import TrackingRef +from codat_sync_for_payables.models.update_connection import UpdateConnection +from codat_sync_for_payables.models.validation import Validation +from codat_sync_for_payables.models.validation_item import ValidationItem +from .sdk import CodatSyncPayables from ._version import ( __title__, @@ -7,11 +115,16 @@ __gen_version__, __user_agent__, ) -from .sdk import * -from .sdkconfiguration import * +VERSION: str = __version__ +OPENAPI_DOC_VERSION: str = __openapi_doc_version__ +USER_AGENT: str = __user_agent__ +SPEAKEASY_GENERATOR_VERSION: str = __gen_version__ +from .utils.retries import ( + RetryConfig as RetryConfig, +) +SERVERS = ['https://api.codat.io'] -VERSION: str = __version__ -OPENAPI_DOC_VERSION = __openapi_doc_version__ -SPEAKEASY_GENERATOR_VERSION = __gen_version__ -USER_AGENT = __user_agent__ + +# The client class's other published spelling. +CodatSyncForPayables = CodatSyncPayables diff --git a/sync-for-payables/src/codat_sync_for_payables/_hooks/__init__.py b/sync-for-payables/src/codat_sync_for_payables/_hooks/__init__.py index e763be4b1..9a9b25d03 100644 --- a/sync-for-payables/src/codat_sync_for_payables/_hooks/__init__.py +++ b/sync-for-payables/src/codat_sync_for_payables/_hooks/__init__.py @@ -1,4 +1,28 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""Hooks public surface.""" -from .sdkhooks import * -from .types import * +from .sdkhooks import SDKHooks, attach_hooks_to_api_client +from .types import ( + AfterErrorContext, + AfterErrorHook, + AfterSuccessContext, + AfterSuccessHook, + BeforeRequestContext, + BeforeRequestHook, + HookContext, + Hooks, + SDKInitHook, +) + +__all__ = [ + "AfterErrorContext", + "AfterErrorHook", + "AfterSuccessContext", + "AfterSuccessHook", + "BeforeRequestContext", + "BeforeRequestHook", + "HookContext", + "Hooks", + "SDKHooks", + "SDKInitHook", + "attach_hooks_to_api_client", +] diff --git a/sync-for-payables/src/codat_sync_for_payables/_hooks/sdkhooks.py b/sync-for-payables/src/codat_sync_for_payables/_hooks/sdkhooks.py index 4e609f86a..d130d2d60 100644 --- a/sync-for-payables/src/codat_sync_for_payables/_hooks/sdkhooks.py +++ b/sync-for-payables/src/codat_sync_for_payables/_hooks/sdkhooks.py @@ -1,18 +1,22 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""SDKHooks registry — mirrors Speakeasy's _hooks/sdkhooks.py. -import httpx +Generated by pipeline/postprocess_generated.py — do not edit by hand. +""" + +from typing import Any, List, Optional, Tuple + +from .registration import init_hooks from .types import ( - SDKInitHook, - BeforeRequestContext, - BeforeRequestHook, - AfterSuccessContext, - AfterSuccessHook, AfterErrorContext, AfterErrorHook, + AfterSuccessContext, + AfterSuccessHook, + BeforeRequestContext, + BeforeRequestHook, + HookContext, Hooks, + SDKInitHook, ) -from typing import List, Optional, Tuple -from codat_sync_for_payables.httpclient import HttpClient class SDKHooks(Hooks): @@ -21,6 +25,7 @@ def __init__(self) -> None: 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) @@ -34,25 +39,20 @@ def register_after_success_hook(self, hook: AfterSuccessHook) -> None: def register_after_error_hook(self, hook: AfterErrorHook) -> None: self.after_error_hooks.append(hook) - def sdk_init(self, base_url: str, client: HttpClient) -> Tuple[str, HttpClient]: + def sdk_init(self, base_url: str, client: Any) -> Tuple[str, Any]: 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: httpx.Request - ) -> httpx.Request: + def before_request(self, hook_ctx: BeforeRequestContext, request: Any) -> Any: 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: httpx.Response - ) -> httpx.Response: + def after_success(self, hook_ctx: AfterSuccessContext, response: Any) -> Any: for hook in self.after_success_hooks: out = hook.after_success(hook_ctx, response) if isinstance(out, Exception): @@ -63,12 +63,85 @@ def after_success( def after_error( self, hook_ctx: AfterErrorContext, - response: Optional[httpx.Response], + response: Optional[Any], error: Optional[Exception], - ) -> Tuple[Optional[httpx.Response], Optional[Exception]]: + ) -> Tuple[Optional[Any], 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 + + +def attach_hooks_to_api_client( + api_client: Any, + hooks: SDKHooks, + base_url: str = "", + security_source: Any = None, + auth_headers: Optional[List[Tuple[str, str]]] = None, +) -> None: + """Wrap api_client.call_api so registered hooks fire around each request. + + Notes: + - operation_id is the real spec operation id (e.g. "create-company"), + matching Speakeasy. Each generated method passes it to call_api as the + operation_id keyword; it defaults to "" only if a caller reaches + call_api without going through a generated method. The value comes from + the same source of truth the TypeScript arm uses (the x-codat-operation-id + vendor extension, set in preprocess_oas.py). + - The request and response objects are urllib3-flavoured, not httpx — + consistent with our ApiClient. Hook authors should treat them opaquely. + - security_source is the value passed to the SDK constructor. It may be a + Security model or a zero-argument callable that returns one (Speakeasy's + pattern for rotating credentials). It is resolved on every request so a + rotating credential is picked up each time, and each (field, header) in + auth_headers is set from the resolved value. + """ + original_call_api = api_client.call_api + resolved_auth_headers = auth_headers or [] + + def apply_security(headers): + if security_source is None or not resolved_auth_headers: + return + resolved = security_source() if callable(security_source) else security_source + for field_name, header_name in resolved_auth_headers: + value = getattr(resolved, field_name, None) + if value is not None: + headers[header_name] = value + + def wrapped(method, url, header_params=None, body=None, post_params=None, _request_timeout=None, operation_id=""): + headers = dict(header_params or {}) + apply_security(headers) + hook_ctx = HookContext( + config=None, + base_url=base_url, + operation_id=operation_id, + oauth2_scopes=None, + security_source=security_source, + ) + request = { + "method": method, + "url": url, + "headers": headers, + "body": body, + "post_params": post_params, + } + request = hooks.before_request(BeforeRequestContext(hook_ctx), request) + try: + response = original_call_api( + method=request["method"], + url=request["url"], + header_params=request["headers"], + body=request["body"], + post_params=request.get("post_params"), + _request_timeout=_request_timeout, + ) + except Exception as e: + new_response, new_error = hooks.after_error(AfterErrorContext(hook_ctx), None, e) + if new_error is not None: + raise new_error + return new_response + return hooks.after_success(AfterSuccessContext(hook_ctx), response) + + api_client.call_api = wrapped diff --git a/sync-for-payables/src/codat_sync_for_payables/_hooks/types.py b/sync-for-payables/src/codat_sync_for_payables/_hooks/types.py index 4c4a0dfe5..5abf97b02 100644 --- a/sync-for-payables/src/codat_sync_for_payables/_hooks/types.py +++ b/sync-for-payables/src/codat_sync_for_payables/_hooks/types.py @@ -1,14 +1,26 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""Hooks abstract surface — mirrors Speakeasy's _hooks/types.py. + +Generated by pipeline/postprocess_generated.py — do not edit by hand. + +Class names and method signatures match Speakeasy bit-for-bit so SDK-author code +that registers hook implementations can be ported unchanged. The two deviations +from the Speakeasy SDK are intentional and documented in FEATURE-AUDIT.md: + + 1. Request/response types are typed as Any here. Speakeasy uses httpx.Request / + httpx.Response. Our OAG pipeline uses urllib3 via ApiClient, so we use Any + to avoid forcing httpx as a transitive dependency. Hook implementations + should treat the request and response parameters as opaque dicts/objects + produced by ApiClient. + 2. HookContext.config is Any. Speakeasy ships an SDKConfiguration class; we + do not. +""" from abc import ABC, abstractmethod -from codat_sync_for_payables.httpclient import HttpClient -from codat_sync_for_payables.sdkconfiguration import SDKConfiguration -import httpx from typing import Any, Callable, List, Optional, Tuple, Union class HookContext: - config: SDKConfiguration + config: Any base_url: str operation_id: str oauth2_scopes: Optional[List[str]] = None @@ -16,12 +28,12 @@ class HookContext: def __init__( self, - config: SDKConfiguration, + config: Any, base_url: str, operation_id: str, - oauth2_scopes: Optional[List[str]], - security_source: Optional[Union[Any, Callable[[], Any]]], - ): + oauth2_scopes: Optional[List[str]] = None, + security_source: Optional[Union[Any, Callable[[], Any]]] = None, + ) -> None: self.config = config self.base_url = base_url self.operation_id = operation_id @@ -64,24 +76,20 @@ def __init__(self, hook_ctx: HookContext): class SDKInitHook(ABC): @abstractmethod - def sdk_init(self, base_url: str, client: HttpClient) -> Tuple[str, HttpClient]: - pass + def sdk_init(self, base_url: str, client: Any) -> Tuple[str, Any]: + ... class BeforeRequestHook(ABC): @abstractmethod - def before_request( - self, hook_ctx: BeforeRequestContext, request: httpx.Request - ) -> Union[httpx.Request, Exception]: - pass + def before_request(self, hook_ctx: BeforeRequestContext, request: Any) -> Union[Any, Exception]: + ... class AfterSuccessHook(ABC): @abstractmethod - def after_success( - self, hook_ctx: AfterSuccessContext, response: httpx.Response - ) -> Union[httpx.Response, Exception]: - pass + def after_success(self, hook_ctx: AfterSuccessContext, response: Any) -> Union[Any, Exception]: + ... class AfterErrorHook(ABC): @@ -89,25 +97,25 @@ class AfterErrorHook(ABC): def after_error( self, hook_ctx: AfterErrorContext, - response: Optional[httpx.Response], + response: Optional[Any], error: Optional[Exception], - ) -> Union[Tuple[Optional[httpx.Response], Optional[Exception]], Exception]: - pass + ) -> Union[Tuple[Optional[Any], Optional[Exception]], Exception]: + ... class Hooks(ABC): @abstractmethod - def register_sdk_init_hook(self, hook: SDKInitHook): - pass + def register_sdk_init_hook(self, hook: SDKInitHook) -> None: + ... @abstractmethod - def register_before_request_hook(self, hook: BeforeRequestHook): - pass + def register_before_request_hook(self, hook: BeforeRequestHook) -> None: + ... @abstractmethod - def register_after_success_hook(self, hook: AfterSuccessHook): - pass + def register_after_success_hook(self, hook: AfterSuccessHook) -> None: + ... @abstractmethod - def register_after_error_hook(self, hook: AfterErrorHook): - pass + def register_after_error_hook(self, hook: AfterErrorHook) -> None: + ... diff --git a/sync-for-payables/src/codat_sync_for_payables/_httpx_transport.py b/sync-for-payables/src/codat_sync_for_payables/_httpx_transport.py new file mode 100644 index 000000000..68ec2095f --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/_httpx_transport.py @@ -0,0 +1,130 @@ +"""Adapter that routes SDK requests through a consumer-passed httpx.Client. + +Generated by pipeline/postprocess_generated.py — do not edit by hand. + +Exposes the same request() surface as the generated urllib3 RESTClientObject, +so the consumer's proxies, TLS settings, and instrumentation apply to every +request (the Speakeasy SDK behaviour for the `client` constructor kwarg). +""" + +import io +import json +import re + +from .exceptions import ApiException, ApiValueError + + +class HttpxRestResponse(io.IOBase): + + def __init__(self, resp) -> None: + self.response = resp + self.status = resp.status_code + self.reason = resp.reason_phrase + self.data = None + + def read(self): + if self.data is None: + self.data = self.response.content + return self.data + + def getheaders(self): + """Returns the response headers (case-insensitive mapping).""" + return self.response.headers + + def getheader(self, name, default=None): + """Returns a given response header.""" + return self.response.headers.get(name, default) + + +def _to_httpx_timeout(request_timeout): + """Map the generated stack's timeout (number or (connect, read) pair) onto + an httpx.Timeout. None means: use the passed client's own default.""" + if request_timeout is None: + return None + import httpx + + if isinstance(request_timeout, (int, float)): + return httpx.Timeout(request_timeout) + connect, read = request_timeout + return httpx.Timeout(read, connect=connect) + + +class HttpxRestClient: + + def __init__(self, client) -> None: + self.client = client + + def request( + self, + method, + url, + headers=None, + body=None, + post_params=None, + _request_timeout=None, + ): + method = method.upper() + assert method in [ + "GET", + "HEAD", + "DELETE", + "POST", + "PUT", + "PATCH", + "OPTIONS", + ] + + if post_params and body: + raise ApiValueError( + "body parameter cannot be used with post_params parameter." + ) + + post_params = post_params or [] + headers = dict(headers or {}) + + content = None + data = None + files = None + + if method in ["POST", "PUT", "PATCH", "OPTIONS", "DELETE"]: + content_type = headers.get("Content-Type") + if not content_type or re.search("json", content_type, re.IGNORECASE): + if body is not None: + content = json.dumps(body) + elif content_type == "application/x-www-form-urlencoded": + data = dict(post_params) + elif content_type == "multipart/form-data": + # httpx must set the Content-Type itself to carry the boundary. + del headers["Content-Type"] + data = {} + files = [] + for name, value in post_params: + if isinstance(value, tuple) and len(value) == 3: + files.append((name, value)) + elif isinstance(value, dict): + data[name] = json.dumps(value) + else: + data[name] = value + elif isinstance(body, (str, bytes)): + content = body + elif content_type.startswith("text/") and isinstance(body, bool): + content = "true" if body else "false" + else: + msg = """Cannot prepare a request message for provided + arguments. Please check that your arguments match + declared content type.""" + raise ApiException(status=0, reason=msg) + + request_kwargs = {"headers": headers} + if content is not None: + request_kwargs["content"] = content + if data is not None: + request_kwargs["data"] = data + if files: + request_kwargs["files"] = files + timeout = _to_httpx_timeout(_request_timeout) + if timeout is not None: + request_kwargs["timeout"] = timeout + + resp = self.client.request(method, url, **request_kwargs) + return HttpxRestResponse(resp) diff --git a/sync-for-payables/src/codat_sync_for_payables/_version.py b/sync-for-payables/src/codat_sync_for_payables/_version.py index b8ba1219a..19ecf21d6 100644 --- a/sync-for-payables/src/codat_sync_for_payables/_version.py +++ b/sync-for-payables/src/codat_sync_for_payables/_version.py @@ -1,12 +1,17 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""Version metadata for codat-sync-for-payables. + +Generated by pipeline/postprocess_generated.py — do not edit by hand. +""" + +from __future__ import annotations import importlib.metadata __title__: str = "codat-sync-for-payables" -__version__: str = "9.1.0" +__version__: str = "3.0.0" __openapi_doc_version__: str = "3.0.0" -__gen_version__: str = "2.893.0" -__user_agent__: str = "speakeasy-sdk/python 9.1.0 2.893.0 3.0.0 codat-sync-for-payables" +__gen_version__: str = "codat-sdk-codegen-poc-0.1.0" +__user_agent__: str = "codat-sdk/python 3.0.0 codat-sdk-codegen-poc-0.1.0 3.0.0 codat-sync-for-payables" try: if __package__ is not None: diff --git a/sync-for-payables/src/codat_sync_for_payables/api/__init__.py b/sync-for-payables/src/codat_sync_for_payables/api/__init__.py new file mode 100644 index 000000000..0778db317 --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/api/__init__.py @@ -0,0 +1,11 @@ +# flake8: noqa + +# import apis into api package +from codat_sync_for_payables.api.bank_accounts import BankAccounts +from codat_sync_for_payables.api.bill_payments import BillPayments +from codat_sync_for_payables.api.bills import Bills +from codat_sync_for_payables.api.companies import Companies +from codat_sync_for_payables.api.company_information import CompanyInformation +from codat_sync_for_payables.api.connections import Connections +from codat_sync_for_payables.api.suppliers import Suppliers + diff --git a/sync-for-payables/src/codat_sync_for_payables/api/bank_accounts.py b/sync-for-payables/src/codat_sync_for_payables/api/bank_accounts.py new file mode 100644 index 000000000..72e0d5530 --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/api/bank_accounts.py @@ -0,0 +1,293 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +import asyncio +import warnings +from pydantic import BaseModel, model_serializer, validate_call, Field +from typing import Any, Dict, List, Mapping, Optional, Tuple, Union +from typing_extensions import Annotated, NotRequired, TypedDict + +from pydantic import Field +from typing import Optional +from typing_extensions import Annotated +from codat_sync_for_payables.models.shared.bill import Bill +from codat_sync_for_payables.models.shared.bills import Bills +from codat_sync_for_payables.models.shared.companies import Companies +from codat_sync_for_payables.models.shared.company import Company +from codat_sync_for_payables.models.shared.connections import Connections +from codat_sync_for_payables.models.shared.suppliers import Suppliers +from codat_sync_for_payables.models.shared.bankaccount import BankAccount +from codat_sync_for_payables.models.shared.bankaccountprototype import BankAccountPrototype + +from codat_sync_for_payables.api_client import ApiClient, RequestSerialized +from codat_sync_for_payables.api_response import ApiResponse +from codat_sync_for_payables.exceptions import ApiException +from codat_sync_for_payables.models.errors import ErrorMessage, SDKError +from codat_sync_for_payables.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_sync_for_payables.rest import RESTResponseType +from codat_sync_for_payables.types import UNSET, OptionalNullable +from codat_sync_for_payables.utils.retries import RetryConfig, execute_with_retries + + +class CreateBankAccountRequestTypedDict(TypedDict): + """TypedDict variant of CreateBankAccountRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + idempotency_key: NotRequired[Annotated[Optional[str], Field(description="A unique identifier to ensure idempotent behaviour for subsequent requests.")]] + bank_account_prototype: NotRequired[Optional[BankAccountPrototype]] + + +class CreateBankAccountRequest(BaseModel): + """Request envelope for create_bank_account.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + idempotency_key: Annotated[Optional[str], Field(description="A unique identifier to ensure idempotent behaviour for subsequent requests.")] = None + bank_account_prototype: Optional[BankAccountPrototype] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class BankAccounts: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call(config={"arbitrary_types_allowed": True}) + def create( + self, + *, + request: Union['CreateBankAccountRequest', 'CreateBankAccountRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> BankAccount: + """Create bank account""" # noqa: E501 + + if isinstance(request, dict): + request = CreateBankAccountRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._create_bank_account_serialize( + company_id=request.company_id, + connection_id=request.connection_id, + idempotency_key=request.idempotency_key, + bank_account_prototype=request.bank_account_prototype, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "BankAccount", + '400': "ErrorMessage", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='create-bank-account', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def create_async( + self, + *, + request: Union['CreateBankAccountRequest', 'CreateBankAccountRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> BankAccount: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.create( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _create_bank_account_serialize( + self, + company_id, + connection_id, + idempotency_key, + bank_account_prototype, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + if connection_id is not None: + _path_params['connectionId'] = connection_id + # process the query parameters + # process the header parameters + if idempotency_key is not None: + _header_params['Idempotency-Key'] = idempotency_key + # process the form parameters + # process the body parameter + if bank_account_prototype is not None: + _body_params = bank_account_prototype + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/companies/{companyId}/connections/{connectionId}/payables/bankAccounts', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/sync-for-payables/src/codat_sync_for_payables/api/bill_payments.py b/sync-for-payables/src/codat_sync_for_payables/api/bill_payments.py new file mode 100644 index 000000000..763ad4ba8 --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/api/bill_payments.py @@ -0,0 +1,533 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +import asyncio +import warnings +from pydantic import BaseModel, model_serializer, validate_call, Field +from typing import Any, Dict, List, Mapping, Optional, Tuple, Union +from typing_extensions import Annotated, NotRequired, TypedDict + +from pydantic import Field +from typing import Optional +from typing_extensions import Annotated +from codat_sync_for_payables.models.shared.bill import Bill +from codat_sync_for_payables.models.shared.bills import Bills +from codat_sync_for_payables.models.shared.companies import Companies +from codat_sync_for_payables.models.shared.company import Company +from codat_sync_for_payables.models.shared.connections import Connections +from codat_sync_for_payables.models.shared.suppliers import Suppliers +from codat_sync_for_payables.models.shared.billpayment import BillPayment +from codat_sync_for_payables.models.shared.billpaymentprototype import BillPaymentPrototype +from codat_sync_for_payables.models.shared.paymentmappingoptions import PaymentMappingOptions + +from codat_sync_for_payables.api_client import ApiClient, RequestSerialized +from codat_sync_for_payables.api_response import ApiResponse +from codat_sync_for_payables.exceptions import ApiException +from codat_sync_for_payables.models.errors import ErrorMessage, SDKError +from codat_sync_for_payables.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_sync_for_payables.rest import RESTResponseType +from codat_sync_for_payables.types import UNSET, OptionalNullable +from codat_sync_for_payables.utils.retries import RetryConfig, execute_with_retries + + +class CreateBillPaymentRequestTypedDict(TypedDict): + """TypedDict variant of CreateBillPaymentRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + bill_id: Annotated[str, Field(description="Unique identifier for a bill.")] + idempotency_key: NotRequired[Annotated[Optional[str], Field(description="A unique identifier to ensure idempotent behaviour for subsequent requests.")]] + bill_payment_prototype: NotRequired[Optional[BillPaymentPrototype]] + + +class CreateBillPaymentRequest(BaseModel): + """Request envelope for create_bill_payment.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + bill_id: Annotated[str, Field(description="Unique identifier for a bill.")] + idempotency_key: Annotated[Optional[str], Field(description="A unique identifier to ensure idempotent behaviour for subsequent requests.")] = None + bill_payment_prototype: Optional[BillPaymentPrototype] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class GetMappingOptionsPaymentsRequestTypedDict(TypedDict): + """TypedDict variant of GetMappingOptionsPaymentsRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + continuation_token: NotRequired[Annotated[Optional[str], Field(description="Retrieve the next page of results using the continuation token from the previous response.")]] + status_query: NotRequired[Annotated[Optional[str], Field(description="Codat query string allows you to filter by `status` (`status=Active||status=Archived`). [Learn more](https://docs.codat.io/using-the-api/querying) about Codat's query string.")]] + + +class GetMappingOptionsPaymentsRequest(BaseModel): + """Request envelope for get_mapping_options_payments.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + continuation_token: Annotated[Optional[str], Field(description="Retrieve the next page of results using the continuation token from the previous response.")] = None + status_query: Annotated[Optional[str], Field(description="Codat query string allows you to filter by `status` (`status=Active||status=Archived`). [Learn more](https://docs.codat.io/using-the-api/querying) about Codat's query string.")] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class BillPayments: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call(config={"arbitrary_types_allowed": True}) + def create( + self, + *, + request: Union['CreateBillPaymentRequest', 'CreateBillPaymentRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> BillPayment: + """Create bill payment""" # noqa: E501 + + if isinstance(request, dict): + request = CreateBillPaymentRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._create_bill_payment_serialize( + company_id=request.company_id, + connection_id=request.connection_id, + bill_id=request.bill_id, + idempotency_key=request.idempotency_key, + bill_payment_prototype=request.bill_payment_prototype, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "BillPayment", + '400': "ErrorMessage", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '409': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='create-bill-payment', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def create_async( + self, + *, + request: Union['CreateBillPaymentRequest', 'CreateBillPaymentRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> BillPayment: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.create( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _create_bill_payment_serialize( + self, + company_id, + connection_id, + bill_id, + idempotency_key, + bill_payment_prototype, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + if connection_id is not None: + _path_params['connectionId'] = connection_id + if bill_id is not None: + _path_params['billId'] = bill_id + # process the query parameters + # process the header parameters + if idempotency_key is not None: + _header_params['Idempotency-Key'] = idempotency_key + # process the form parameters + # process the body parameter + if bill_payment_prototype is not None: + _body_params = bill_payment_prototype + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/companies/{companyId}/connections/{connectionId}/payables/bills/{billId}/payment', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def get_payment_options( + self, + *, + request: Union['GetMappingOptionsPaymentsRequest', 'GetMappingOptionsPaymentsRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> PaymentMappingOptions: + """Get payment mapping options""" # noqa: E501 + + if isinstance(request, dict): + request = GetMappingOptionsPaymentsRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._get_mapping_options_payments_serialize( + company_id=request.company_id, + connection_id=request.connection_id, + continuation_token=request.continuation_token, + status_query=request.status_query, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "PaymentMappingOptions", + '400': "ErrorMessage", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='get-mapping-options-payments', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def get_payment_options_async( + self, + *, + request: Union['GetMappingOptionsPaymentsRequest', 'GetMappingOptionsPaymentsRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> PaymentMappingOptions: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.get_payment_options( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _get_mapping_options_payments_serialize( + self, + company_id, + connection_id, + continuation_token, + status_query, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + if connection_id is not None: + _path_params['connectionId'] = connection_id + # process the query parameters + if continuation_token is not None: + + _query_params.append(('continuationToken', continuation_token)) + + if status_query is not None: + + _query_params.append(('statusQuery', status_query)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/companies/{companyId}/connections/{connectionId}/payables/mappingOptions/payments', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/sync-for-payables/src/codat_sync_for_payables/api/bills.py b/sync-for-payables/src/codat_sync_for_payables/api/bills.py new file mode 100644 index 000000000..e4dba220b --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/api/bills.py @@ -0,0 +1,1724 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +import asyncio +import httpx +import warnings +from pydantic import BaseModel, model_serializer, validate_call, Field +from typing import Any, Dict, List, Mapping, Optional, Tuple, Union +from typing_extensions import Annotated, NotRequired, TypedDict + +from pydantic import Field +from typing import List, Optional, Tuple, Union +from typing_extensions import Annotated +from codat_sync_for_payables.models.shared.companies import Companies +from codat_sync_for_payables.models.shared.attachmentupload import AttachmentUpload +from codat_sync_for_payables.models.shared.company import Company +from codat_sync_for_payables.models.shared.connections import Connections +from codat_sync_for_payables.models.shared.suppliers import Suppliers +from codat_sync_for_payables.models.shared.bill import Bill +from codat_sync_for_payables.models.shared.billmappingoptions import BillMappingOptions +from codat_sync_for_payables.models.shared.billprototype import BillPrototype +from codat_sync_for_payables.models.shared.bills import Bills + +from codat_sync_for_payables.api_client import ApiClient, RequestSerialized +from codat_sync_for_payables.api_response import ApiResponse +from codat_sync_for_payables.exceptions import ApiException +from codat_sync_for_payables.models.errors import ErrorMessage, SDKError +from codat_sync_for_payables.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_sync_for_payables.rest import RESTResponseType +from codat_sync_for_payables.types import UNSET, OptionalNullable +from codat_sync_for_payables.utils.retries import RetryConfig, execute_with_retries +from codat_sync_for_payables.models.shared.attachment import Attachment + + + + +def _wrap_binary_to_httpx_response(data, content_type=None): + """Wrap raw binary response data into an httpx.Response so callers + can rely on .status_code / .headers / .content / .read() as they + would with the Speakeasy SDK. The data we get from OAG is the + decoded body bytes — status code is 200 by construction (errors + raised earlier as SDKError). content_type is the op's 2xx media + type, set as the response Content-Type header so a consumer reading + it gets the media type Speakeasy carries. + """ + if isinstance(data, httpx.Response): + return data + if data is None: + content = b'' + elif isinstance(data, (bytes, bytearray, memoryview)): + content = bytes(data) + else: + content = bytes(str(data), 'utf-8') + headers = {'content-type': content_type} if content_type else None + return httpx.Response(status_code=200, content=content, headers=headers) + + +class CreateBillRequestTypedDict(TypedDict): + """TypedDict variant of CreateBillRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + idempotency_key: NotRequired[Annotated[Optional[str], Field(description="A unique identifier to ensure idempotent behaviour for subsequent requests.")]] + bill_prototype: NotRequired[Optional[BillPrototype]] + + +class CreateBillRequest(BaseModel): + """Request envelope for create_bill.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + idempotency_key: Annotated[Optional[str], Field(description="A unique identifier to ensure idempotent behaviour for subsequent requests.")] = None + bill_prototype: Optional[BillPrototype] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class DownloadBillAttachmentRequestTypedDict(TypedDict): + """TypedDict variant of DownloadBillAttachmentRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + bill_id: Annotated[str, Field(description="Unique identifier for a bill.")] + attachment_id: Annotated[str, Field(description="Unique identifier for an attachment.")] + + +class DownloadBillAttachmentRequest(BaseModel): + """Request envelope for download_bill_attachment.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + bill_id: Annotated[str, Field(description="Unique identifier for a bill.")] + attachment_id: Annotated[str, Field(description="Unique identifier for an attachment.")] + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class GetMappingOptionsBillsRequestTypedDict(TypedDict): + """TypedDict variant of GetMappingOptionsBillsRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + continuation_token: NotRequired[Annotated[Optional[str], Field(description="Retrieve the next page of results using the continuation token from the previous response.")]] + status_query: NotRequired[Annotated[Optional[str], Field(description="Codat query string allows you to filter by `status` (`status=Active||status=Archived`). [Learn more](https://docs.codat.io/using-the-api/querying) about Codat's query string.")]] + + +class GetMappingOptionsBillsRequest(BaseModel): + """Request envelope for get_mapping_options_bills.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + continuation_token: Annotated[Optional[str], Field(description="Retrieve the next page of results using the continuation token from the previous response.")] = None + status_query: Annotated[Optional[str], Field(description="Codat query string allows you to filter by `status` (`status=Active||status=Archived`). [Learn more](https://docs.codat.io/using-the-api/querying) about Codat's query string.")] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class ListBillAttachmentsRequestTypedDict(TypedDict): + """TypedDict variant of ListBillAttachmentsRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + bill_id: Annotated[str, Field(description="Unique identifier for a bill.")] + + +class ListBillAttachmentsRequest(BaseModel): + """Request envelope for list_bill_attachments.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + bill_id: Annotated[str, Field(description="Unique identifier for a bill.")] + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class ListBillsRequestTypedDict(TypedDict): + """TypedDict variant of ListBillsRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + continuation_token: NotRequired[Annotated[Optional[str], Field(description="Retrieve the next page of results using the continuation token from the previous response.")]] + query: NotRequired[Annotated[Optional[str], Field(description="Codat query string allows you to filter by `status` and `sourceModifiedDate`. Learn more about Codat's query string [here](https://docs.codat.io/using-the-api/querying). Platfrom specfic statuses: Xero supports Open | PartiallyPaid | Paid | Void | Draft. Qbo supports Open | PartiallyPaid | Paid. FreeAgent supports Open | PartiallyPaid | Paid.")]] + + +class ListBillsRequest(BaseModel): + """Request envelope for list_bills.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + continuation_token: Annotated[Optional[str], Field(description="Retrieve the next page of results using the continuation token from the previous response.")] = None + query: Annotated[Optional[str], Field(description="Codat query string allows you to filter by `status` and `sourceModifiedDate`. Learn more about Codat's query string [here](https://docs.codat.io/using-the-api/querying). Platfrom specfic statuses: Xero supports Open | PartiallyPaid | Paid | Void | Draft. Qbo supports Open | PartiallyPaid | Paid. FreeAgent supports Open | PartiallyPaid | Paid.")] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class UpdateBillRequestTypedDict(TypedDict): + """TypedDict variant of UpdateBillRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + bill_id: Annotated[str, Field(description="Unique identifier for a bill.")] + idempotency_key: NotRequired[Annotated[Optional[str], Field(description="A unique identifier to ensure idempotent behaviour for subsequent requests.")]] + bill_prototype: NotRequired[Optional[BillPrototype]] + + +class UpdateBillRequest(BaseModel): + """Request envelope for update_bill.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + bill_id: Annotated[str, Field(description="Unique identifier for a bill.")] + idempotency_key: Annotated[Optional[str], Field(description="A unique identifier to ensure idempotent behaviour for subsequent requests.")] = None + bill_prototype: Optional[BillPrototype] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class UploadBillAttachmentRequestTypedDict(TypedDict): + """TypedDict variant of UploadBillAttachmentRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + bill_id: Annotated[str, Field(description="Unique identifier for a bill.")] + attachment_upload: NotRequired[Optional[AttachmentUpload]] + + +class UploadBillAttachmentRequest(BaseModel): + """Request envelope for upload_bill_attachment.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + bill_id: Annotated[str, Field(description="Unique identifier for a bill.")] + attachment_upload: Optional[AttachmentUpload] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class Bills: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call(config={"arbitrary_types_allowed": True}) + def create( + self, + *, + request: Union['CreateBillRequest', 'CreateBillRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Bill: + """Create bill""" # noqa: E501 + + if isinstance(request, dict): + request = CreateBillRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._create_bill_serialize( + company_id=request.company_id, + connection_id=request.connection_id, + idempotency_key=request.idempotency_key, + bill_prototype=request.bill_prototype, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "Bill", + '400': "ErrorMessage", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '409': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='create-bill', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def create_async( + self, + *, + request: Union['CreateBillRequest', 'CreateBillRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Bill: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.create( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _create_bill_serialize( + self, + company_id, + connection_id, + idempotency_key, + bill_prototype, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + if connection_id is not None: + _path_params['connectionId'] = connection_id + # process the query parameters + # process the header parameters + if idempotency_key is not None: + _header_params['Idempotency-Key'] = idempotency_key + # process the form parameters + # process the body parameter + if bill_prototype is not None: + _body_params = bill_prototype + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/companies/{companyId}/connections/{connectionId}/payables/bills', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def download_attachment( + self, + *, + request: Union['DownloadBillAttachmentRequest', 'DownloadBillAttachmentRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> httpx.Response: + """Download bill attachment""" # noqa: E501 + + if isinstance(request, dict): + request = DownloadBillAttachmentRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._download_bill_attachment_serialize( + company_id=request.company_id, + connection_id=request.connection_id, + bill_id=request.bill_id, + attachment_id=request.attachment_id, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "bytearray", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='download-bill-attachment', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return _wrap_binary_to_httpx_response(execute_with_retries(_do_call, _effective_retries), 'application/octet-stream') + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def download_attachment_async( + self, + *, + request: Union['DownloadBillAttachmentRequest', 'DownloadBillAttachmentRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> httpx.Response: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.download_attachment( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _download_bill_attachment_serialize( + self, + company_id, + connection_id, + bill_id, + attachment_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + if connection_id is not None: + _path_params['connectionId'] = connection_id + if bill_id is not None: + _path_params['billId'] = bill_id + if attachment_id is not None: + _path_params['attachmentId'] = attachment_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = 'application/octet-stream' + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/companies/{companyId}/connections/{connectionId}/payables/bills/{billId}/attachments/{attachmentId}/download', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def get_bill_options( + self, + *, + request: Union['GetMappingOptionsBillsRequest', 'GetMappingOptionsBillsRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> BillMappingOptions: + """Get bill mapping options""" # noqa: E501 + + if isinstance(request, dict): + request = GetMappingOptionsBillsRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._get_mapping_options_bills_serialize( + company_id=request.company_id, + connection_id=request.connection_id, + continuation_token=request.continuation_token, + status_query=request.status_query, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "BillMappingOptions", + '400': "ErrorMessage", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='get-mapping-options-bills', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def get_bill_options_async( + self, + *, + request: Union['GetMappingOptionsBillsRequest', 'GetMappingOptionsBillsRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> BillMappingOptions: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.get_bill_options( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _get_mapping_options_bills_serialize( + self, + company_id, + connection_id, + continuation_token, + status_query, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + if connection_id is not None: + _path_params['connectionId'] = connection_id + # process the query parameters + if continuation_token is not None: + + _query_params.append(('continuationToken', continuation_token)) + + if status_query is not None: + + _query_params.append(('statusQuery', status_query)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/companies/{companyId}/connections/{connectionId}/payables/mappingOptions/bills', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def list_attachments( + self, + *, + request: Union['ListBillAttachmentsRequest', 'ListBillAttachmentsRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> List[Attachment]: + """List bill attachments""" # noqa: E501 + + if isinstance(request, dict): + request = ListBillAttachmentsRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._list_bill_attachments_serialize( + company_id=request.company_id, + connection_id=request.connection_id, + bill_id=request.bill_id, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Attachment]", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '409': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='list-bill-attachments', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def list_attachments_async( + self, + *, + request: Union['ListBillAttachmentsRequest', 'ListBillAttachmentsRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> List[Attachment]: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.list_attachments( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _list_bill_attachments_serialize( + self, + company_id, + connection_id, + bill_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + if connection_id is not None: + _path_params['connectionId'] = connection_id + if bill_id is not None: + _path_params['billId'] = bill_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/companies/{companyId}/connections/{connectionId}/payables/bills/{billId}/attachments', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def list( + self, + *, + request: Union['ListBillsRequest', 'ListBillsRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Bills: + """List bills""" # noqa: E501 + + if isinstance(request, dict): + request = ListBillsRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._list_bills_serialize( + company_id=request.company_id, + connection_id=request.connection_id, + continuation_token=request.continuation_token, + query=request.query, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Bills", + '400': "ErrorMessage", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '409': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='list-bills', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def list_async( + self, + *, + request: Union['ListBillsRequest', 'ListBillsRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Bills: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.list( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _list_bills_serialize( + self, + company_id, + connection_id, + continuation_token, + query, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + if connection_id is not None: + _path_params['connectionId'] = connection_id + # process the query parameters + if continuation_token is not None: + + _query_params.append(('continuationToken', continuation_token)) + + if query is not None: + + _query_params.append(('query', query)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/companies/{companyId}/connections/{connectionId}/payables/bills', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def update( + self, + *, + request: Union['UpdateBillRequest', 'UpdateBillRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Bill: + """Update bill""" # noqa: E501 + + if isinstance(request, dict): + request = UpdateBillRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._update_bill_serialize( + company_id=request.company_id, + connection_id=request.connection_id, + bill_id=request.bill_id, + idempotency_key=request.idempotency_key, + bill_prototype=request.bill_prototype, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Bill", + '400': "ErrorMessage", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '409': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='update-bill', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def update_async( + self, + *, + request: Union['UpdateBillRequest', 'UpdateBillRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Bill: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.update( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _update_bill_serialize( + self, + company_id, + connection_id, + bill_id, + idempotency_key, + bill_prototype, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + if connection_id is not None: + _path_params['connectionId'] = connection_id + if bill_id is not None: + _path_params['billId'] = bill_id + # process the query parameters + # process the header parameters + if idempotency_key is not None: + _header_params['Idempotency-Key'] = idempotency_key + # process the form parameters + # process the body parameter + if bill_prototype is not None: + _body_params = bill_prototype + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='PUT', + resource_path='/companies/{companyId}/connections/{connectionId}/payables/bills/{billId}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def upload_attachment( + self, + *, + request: Union['UploadBillAttachmentRequest', 'UploadBillAttachmentRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Attachment: + """Upload bill attachment""" # noqa: E501 + + if isinstance(request, dict): + request = UploadBillAttachmentRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._upload_bill_attachment_serialize( + company_id=request.company_id, + connection_id=request.connection_id, + bill_id=request.bill_id, + attachment_upload=request.attachment_upload, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "Attachment", + '400': "ErrorMessage", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='upload-bill-attachment', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def upload_attachment_async( + self, + *, + request: Union['UploadBillAttachmentRequest', 'UploadBillAttachmentRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Attachment: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.upload_attachment( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _upload_bill_attachment_serialize( + self, + company_id, + connection_id, + bill_id, + attachment_upload, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + if connection_id is not None: + _path_params['connectionId'] = connection_id + if bill_id is not None: + _path_params['billId'] = bill_id + # process the query parameters + # process the header parameters + # process the form parameters + if attachment_upload is not None and attachment_upload.file is not None: + _cf = attachment_upload.file + # 3-tuple carries content_type onto the multipart part (matching Speakeasy's + # serialize_multipart_form); the 2-tuple lets files_parameters guess it. + _files['file'] = ( + (_cf.file_name, _cf.content, _cf.content_type) + if _cf.content_type is not None + else (_cf.file_name, _cf.content) + ) + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'multipart/form-data' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/companies/{companyId}/connections/{connectionId}/payables/bills/{billId}/attachments', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/sync-for-payables/src/codat_sync_for_payables/api/companies.py b/sync-for-payables/src/codat_sync_for_payables/api/companies.py new file mode 100644 index 000000000..d6aa9128a --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/api/companies.py @@ -0,0 +1,1390 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +import asyncio +import warnings +from pydantic import BaseModel, model_serializer, validate_call, Field +from typing import Any, Dict, List, Mapping, Optional, Tuple, Union +from typing_extensions import Annotated, NotRequired, TypedDict + +from pydantic import Field +from typing import Optional +from typing_extensions import Annotated +from codat_sync_for_payables.models.shared.bill import Bill +from codat_sync_for_payables.models.shared.bills import Bills +from codat_sync_for_payables.models.shared.connections import Connections +from codat_sync_for_payables.models.shared.suppliers import Suppliers +from codat_sync_for_payables.models.shared.companies import Companies +from codat_sync_for_payables.models.shared.company import Company +from codat_sync_for_payables.models.shared.companyrequestbody import CompanyRequestBody, CompanyRequestBodyTypedDict +from codat_sync_for_payables.models.shared.companyupdaterequest import CompanyUpdateRequest + +from codat_sync_for_payables.api_client import ApiClient, RequestSerialized +from codat_sync_for_payables.api_response import ApiResponse +from codat_sync_for_payables.exceptions import ApiException +from codat_sync_for_payables.models.errors import ErrorMessage, SDKError +from codat_sync_for_payables.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_sync_for_payables.rest import RESTResponseType +from codat_sync_for_payables.types import UNSET, OptionalNullable +from codat_sync_for_payables.utils.retries import RetryConfig, execute_with_retries + + +class CreateCompanyRequestTypedDict(TypedDict): + """TypedDict variant of CreateCompanyRequest, for dict-literal request inputs.""" + company_request_body: NotRequired[Optional[CompanyRequestBody]] + + +class CreateCompanyRequest(BaseModel): + """Request envelope for create_company.""" + company_request_body: Optional[CompanyRequestBody] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class DeleteCompanyRequestTypedDict(TypedDict): + """TypedDict variant of DeleteCompanyRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + + +class DeleteCompanyRequest(BaseModel): + """Request envelope for delete_company.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class GetCompanyRequestTypedDict(TypedDict): + """TypedDict variant of GetCompanyRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + + +class GetCompanyRequest(BaseModel): + """Request envelope for get_company.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class ListCompaniesRequestTypedDict(TypedDict): + """TypedDict variant of ListCompaniesRequest, for dict-literal request inputs.""" + page: NotRequired[Annotated[Optional[int], Field(description="Page number. [Read more](https://docs.codat.io/using-the-api/paging).")]] + page_size: NotRequired[Annotated[Optional[int], Field(description="Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging).")]] + query: NotRequired[Annotated[Optional[str], Field(description="Codat query string. [Read more](https://docs.codat.io/using-the-api/querying).")]] + order_by: NotRequired[Annotated[Optional[str], Field(description="Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).")]] + tags: NotRequired[Annotated[Optional[str], Field(description="Filter companies by tags using the \"equals\" (=), \"not equals\" (!=), and \"contains\" (~) operators with [Codat’s query language](https://docs.codat.io/using-the-api/querying).")]] + + +class ListCompaniesRequest(BaseModel): + """Request envelope for list_companies.""" + page: Annotated[Optional[int], Field(description="Page number. [Read more](https://docs.codat.io/using-the-api/paging).")] = 1 + page_size: Annotated[Optional[int], Field(description="Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging).")] = 100 + query: Annotated[Optional[str], Field(description="Codat query string. [Read more](https://docs.codat.io/using-the-api/querying).")] = None + order_by: Annotated[Optional[str], Field(description="Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).")] = None + tags: Annotated[Optional[str], Field(description="Filter companies by tags using the \"equals\" (=), \"not equals\" (!=), and \"contains\" (~) operators with [Codat’s query language](https://docs.codat.io/using-the-api/querying).")] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class ReplaceCompanyRequestTypedDict(TypedDict): + """TypedDict variant of ReplaceCompanyRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + company_request_body: NotRequired[Optional[CompanyRequestBody]] + + +class ReplaceCompanyRequest(BaseModel): + """Request envelope for replace_company.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + company_request_body: Optional[CompanyRequestBody] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class UpdateCompanyRequestTypedDict(TypedDict): + """TypedDict variant of UpdateCompanyRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + company_update_request: NotRequired[Optional[CompanyUpdateRequest]] + + +class UpdateCompanyRequest(BaseModel): + """Request envelope for update_company.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + company_update_request: Optional[CompanyUpdateRequest] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class Companies: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call(config={"arbitrary_types_allowed": True}) + def create( + self, + *, + request: Optional[Union[CompanyRequestBody, CompanyRequestBodyTypedDict]] = None, + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Company: + """Create company""" # noqa: E501 + + if isinstance(request, dict): + request = CompanyRequestBody.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._create_company_serialize( + company_request_body=request, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Company", + '400': "ErrorMessage", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='create-company', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def create_async( + self, + *, + request: Optional[Union[CompanyRequestBody, CompanyRequestBodyTypedDict]] = None, + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Company: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.create( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _create_company_serialize( + self, + company_request_body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if company_request_body is not None: + _body_params = company_request_body + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/companies', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def delete( + self, + *, + request: Union['DeleteCompanyRequest', 'DeleteCompanyRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> None: + """Delete a company""" # noqa: E501 + + if isinstance(request, dict): + request = DeleteCompanyRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._delete_company_serialize( + company_id=request.company_id, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='delete-company', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def delete_async( + self, + *, + request: Union['DeleteCompanyRequest', 'DeleteCompanyRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> None: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.delete( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _delete_company_serialize( + self, + company_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/companies/{companyId}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def get( + self, + *, + request: Union['GetCompanyRequest', 'GetCompanyRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Company: + """Get company""" # noqa: E501 + + if isinstance(request, dict): + request = GetCompanyRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._get_company_serialize( + company_id=request.company_id, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Company", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='get-company', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def get_async( + self, + *, + request: Union['GetCompanyRequest', 'GetCompanyRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Company: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.get( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _get_company_serialize( + self, + company_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/companies/{companyId}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def list( + self, + *, + request: Union['ListCompaniesRequest', 'ListCompaniesRequestTypedDict'] = ListCompaniesRequest(), + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Companies: + """List companies""" # noqa: E501 + + if isinstance(request, dict): + request = ListCompaniesRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._list_companies_serialize( + page=request.page, + page_size=request.page_size, + query=request.query, + order_by=request.order_by, + tags=request.tags, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Companies", + '400': "ErrorMessage", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='list-companies', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def list_async( + self, + *, + request: Union['ListCompaniesRequest', 'ListCompaniesRequestTypedDict'] = ListCompaniesRequest(), + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Companies: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.list( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _list_companies_serialize( + self, + page, + page_size, + query, + order_by, + tags, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if page is not None: + + _query_params.append(('page', page)) + + if page_size is not None: + + _query_params.append(('pageSize', page_size)) + + if query is not None: + + _query_params.append(('query', query)) + + if order_by is not None: + + _query_params.append(('orderBy', order_by)) + + if tags is not None: + + _query_params.append(('tags', tags)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/companies', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def replace( + self, + *, + request: Union['ReplaceCompanyRequest', 'ReplaceCompanyRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Company: + """Replace company""" # noqa: E501 + + if isinstance(request, dict): + request = ReplaceCompanyRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._replace_company_serialize( + company_id=request.company_id, + company_request_body=request.company_request_body, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Company", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='replace-company', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def replace_async( + self, + *, + request: Union['ReplaceCompanyRequest', 'ReplaceCompanyRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Company: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.replace( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _replace_company_serialize( + self, + company_id, + company_request_body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if company_request_body is not None: + _body_params = company_request_body + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='PUT', + resource_path='/companies/{companyId}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def update( + self, + *, + request: Union['UpdateCompanyRequest', 'UpdateCompanyRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Company: + """Update company""" # noqa: E501 + + if isinstance(request, dict): + request = UpdateCompanyRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._update_company_serialize( + company_id=request.company_id, + company_update_request=request.company_update_request, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Company", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='update-company', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def update_async( + self, + *, + request: Union['UpdateCompanyRequest', 'UpdateCompanyRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Company: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.update( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _update_company_serialize( + self, + company_id, + company_update_request, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if company_update_request is not None: + _body_params = company_update_request + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='PATCH', + resource_path='/companies/{companyId}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/sync-for-payables/src/codat_sync_for_payables/api/company_information.py b/sync-for-payables/src/codat_sync_for_payables/api/company_information.py new file mode 100644 index 000000000..00762d803 --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/api/company_information.py @@ -0,0 +1,267 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +import asyncio +import warnings +from pydantic import BaseModel, model_serializer, validate_call, Field +from typing import Any, Dict, List, Mapping, Optional, Tuple, Union +from typing_extensions import Annotated, NotRequired, TypedDict + +from pydantic import Field +from typing_extensions import Annotated +from codat_sync_for_payables.models.shared.bill import Bill +from codat_sync_for_payables.models.shared.bills import Bills +from codat_sync_for_payables.models.shared.companies import Companies +from codat_sync_for_payables.models.shared.company import Company +from codat_sync_for_payables.models.shared.connections import Connections +from codat_sync_for_payables.models.shared.suppliers import Suppliers +from codat_sync_for_payables.models.shared.companyinformation import CompanyInformation + +from codat_sync_for_payables.api_client import ApiClient, RequestSerialized +from codat_sync_for_payables.api_response import ApiResponse +from codat_sync_for_payables.exceptions import ApiException +from codat_sync_for_payables.models.errors import ErrorMessage, SDKError +from codat_sync_for_payables.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_sync_for_payables.rest import RESTResponseType +from codat_sync_for_payables.types import UNSET, OptionalNullable +from codat_sync_for_payables.utils.retries import RetryConfig, execute_with_retries + + +class GetCompanyInformationRequestTypedDict(TypedDict): + """TypedDict variant of GetCompanyInformationRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + + +class GetCompanyInformationRequest(BaseModel): + """Request envelope for get_company_information.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class CompanyInformation: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call(config={"arbitrary_types_allowed": True}) + def get( + self, + *, + request: Union['GetCompanyInformationRequest', 'GetCompanyInformationRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> CompanyInformation: + """Get company information""" # noqa: E501 + + if isinstance(request, dict): + request = GetCompanyInformationRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._get_company_information_serialize( + company_id=request.company_id, + connection_id=request.connection_id, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "CompanyInformation", + '400': "ErrorMessage", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='get-company-information', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def get_async( + self, + *, + request: Union['GetCompanyInformationRequest', 'GetCompanyInformationRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> CompanyInformation: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.get( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _get_company_information_serialize( + self, + company_id, + connection_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + if connection_id is not None: + _path_params['connectionId'] = connection_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/companies/{companyId}/connections/{connectionId}/payables/info', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/sync-for-payables/src/codat_sync_for_payables/api/connections.py b/sync-for-payables/src/codat_sync_for_payables/api/connections.py new file mode 100644 index 000000000..dc846ae2a --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/api/connections.py @@ -0,0 +1,1186 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +import asyncio +import warnings +from pydantic import BaseModel, model_serializer, validate_call, Field +from typing import Any, Dict, List, Mapping, Optional, Tuple, Union +from typing_extensions import Annotated, NotRequired, TypedDict + +from pydantic import Field +from typing import Optional +from typing_extensions import Annotated +from codat_sync_for_payables.models.shared.bill import Bill +from codat_sync_for_payables.models.shared.bills import Bills +from codat_sync_for_payables.models.shared.companies import Companies +from codat_sync_for_payables.models.shared.company import Company +from codat_sync_for_payables.models.shared.suppliers import Suppliers +from codat_sync_for_payables.models.shared.connection import Connection +from codat_sync_for_payables.models.shared.connections import Connections +from codat_sync_for_payables.models.create_connection_request import CreateConnectionRequest as CreateConnectionRequestBody +from codat_sync_for_payables.models.update_connection import UpdateConnection + +from codat_sync_for_payables.api_client import ApiClient, RequestSerialized +from codat_sync_for_payables.api_response import ApiResponse +from codat_sync_for_payables.exceptions import ApiException +from codat_sync_for_payables.models.errors import ErrorMessage, SDKError +from codat_sync_for_payables.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_sync_for_payables.rest import RESTResponseType +from codat_sync_for_payables.types import UNSET, OptionalNullable +from codat_sync_for_payables.utils.retries import RetryConfig, execute_with_retries + + +class CreateConnectionRequestTypedDict(TypedDict): + """TypedDict variant of CreateConnectionRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + request_body: NotRequired[Optional[CreateConnectionRequestBody]] + + +class CreateConnectionRequest(BaseModel): + """Request envelope for create_connection.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + request_body: Optional[CreateConnectionRequestBody] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class DeleteConnectionRequestTypedDict(TypedDict): + """TypedDict variant of DeleteConnectionRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + + +class DeleteConnectionRequest(BaseModel): + """Request envelope for delete_connection.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class GetConnectionRequestTypedDict(TypedDict): + """TypedDict variant of GetConnectionRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + + +class GetConnectionRequest(BaseModel): + """Request envelope for get_connection.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class ListConnectionsRequestTypedDict(TypedDict): + """TypedDict variant of ListConnectionsRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + page: NotRequired[Annotated[Optional[int], Field(description="Page number. [Read more](https://docs.codat.io/using-the-api/paging).")]] + page_size: NotRequired[Annotated[Optional[int], Field(description="Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging).")]] + query: NotRequired[Annotated[Optional[str], Field(description="Codat query string. [Read more](https://docs.codat.io/using-the-api/querying).")]] + order_by: NotRequired[Annotated[Optional[str], Field(description="Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).")]] + + +class ListConnectionsRequest(BaseModel): + """Request envelope for list_connections.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + page: Annotated[Optional[int], Field(description="Page number. [Read more](https://docs.codat.io/using-the-api/paging).")] = 1 + page_size: Annotated[Optional[int], Field(description="Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging).")] = 100 + query: Annotated[Optional[str], Field(description="Codat query string. [Read more](https://docs.codat.io/using-the-api/querying).")] = None + order_by: Annotated[Optional[str], Field(description="Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).")] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class UnlinkConnectionRequestTypedDict(TypedDict): + """TypedDict variant of UnlinkConnectionRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + request_body: NotRequired[Optional[UpdateConnection]] + + +class UnlinkConnectionRequest(BaseModel): + """Request envelope for unlink_connection.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + request_body: Optional[UpdateConnection] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class Connections: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call(config={"arbitrary_types_allowed": True}) + def create( + self, + *, + request: Union['CreateConnectionRequest', 'CreateConnectionRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Connection: + """Create connection""" # noqa: E501 + + if isinstance(request, dict): + request = CreateConnectionRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._create_connection_serialize( + company_id=request.company_id, + request_body=request.request_body, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Connection", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='create-connection', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def create_async( + self, + *, + request: Union['CreateConnectionRequest', 'CreateConnectionRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Connection: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.create( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _create_connection_serialize( + self, + company_id, + request_body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if request_body is not None: + _body_params = request_body + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/companies/{companyId}/connections', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def delete( + self, + *, + request: Union['DeleteConnectionRequest', 'DeleteConnectionRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> None: + """Delete connection""" # noqa: E501 + + if isinstance(request, dict): + request = DeleteConnectionRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._delete_connection_serialize( + company_id=request.company_id, + connection_id=request.connection_id, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='delete-connection', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def delete_async( + self, + *, + request: Union['DeleteConnectionRequest', 'DeleteConnectionRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> None: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.delete( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _delete_connection_serialize( + self, + company_id, + connection_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + if connection_id is not None: + _path_params['connectionId'] = connection_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/companies/{companyId}/connections/{connectionId}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def get( + self, + *, + request: Union['GetConnectionRequest', 'GetConnectionRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Connection: + """Get connection""" # noqa: E501 + + if isinstance(request, dict): + request = GetConnectionRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._get_connection_serialize( + company_id=request.company_id, + connection_id=request.connection_id, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Connection", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='get-connection', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def get_async( + self, + *, + request: Union['GetConnectionRequest', 'GetConnectionRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Connection: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.get( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _get_connection_serialize( + self, + company_id, + connection_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + if connection_id is not None: + _path_params['connectionId'] = connection_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/companies/{companyId}/connections/{connectionId}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def list( + self, + *, + request: Union['ListConnectionsRequest', 'ListConnectionsRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Connections: + """List connections""" # noqa: E501 + + if isinstance(request, dict): + request = ListConnectionsRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._list_connections_serialize( + company_id=request.company_id, + page=request.page, + page_size=request.page_size, + query=request.query, + order_by=request.order_by, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Connections", + '400': "ErrorMessage", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='list-connections', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def list_async( + self, + *, + request: Union['ListConnectionsRequest', 'ListConnectionsRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Connections: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.list( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _list_connections_serialize( + self, + company_id, + page, + page_size, + query, + order_by, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + # process the query parameters + if page is not None: + + _query_params.append(('page', page)) + + if page_size is not None: + + _query_params.append(('pageSize', page_size)) + + if query is not None: + + _query_params.append(('query', query)) + + if order_by is not None: + + _query_params.append(('orderBy', order_by)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/companies/{companyId}/connections', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def unlink( + self, + *, + request: Union['UnlinkConnectionRequest', 'UnlinkConnectionRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Connection: + """Unlink connection""" # noqa: E501 + + if isinstance(request, dict): + request = UnlinkConnectionRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._unlink_connection_serialize( + company_id=request.company_id, + connection_id=request.connection_id, + request_body=request.request_body, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Connection", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='unlink-connection', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def unlink_async( + self, + *, + request: Union['UnlinkConnectionRequest', 'UnlinkConnectionRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Connection: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.unlink( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _unlink_connection_serialize( + self, + company_id, + connection_id, + request_body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + if connection_id is not None: + _path_params['connectionId'] = connection_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if request_body is not None: + _body_params = request_body + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='PATCH', + resource_path='/companies/{companyId}/connections/{connectionId}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/sync-for-payables/src/codat_sync_for_payables/api/suppliers.py b/sync-for-payables/src/codat_sync_for_payables/api/suppliers.py new file mode 100644 index 000000000..9a8d7d624 --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/api/suppliers.py @@ -0,0 +1,766 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +import asyncio +import warnings +from pydantic import BaseModel, model_serializer, validate_call, Field +from typing import Any, Dict, List, Mapping, Optional, Tuple, Union +from typing_extensions import Annotated, NotRequired, TypedDict + +from pydantic import Field +from typing import Optional +from typing_extensions import Annotated +from codat_sync_for_payables.models.shared.bill import Bill +from codat_sync_for_payables.models.shared.bills import Bills +from codat_sync_for_payables.models.shared.companies import Companies +from codat_sync_for_payables.models.shared.company import Company +from codat_sync_for_payables.models.shared.connections import Connections +from codat_sync_for_payables.models.shared.supplier import Supplier +from codat_sync_for_payables.models.shared.supplierprototype import SupplierPrototype +from codat_sync_for_payables.models.shared.suppliers import Suppliers + +from codat_sync_for_payables.api_client import ApiClient, RequestSerialized +from codat_sync_for_payables.api_response import ApiResponse +from codat_sync_for_payables.exceptions import ApiException +from codat_sync_for_payables.models.errors import ErrorMessage, SDKError +from codat_sync_for_payables.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_sync_for_payables.rest import RESTResponseType +from codat_sync_for_payables.types import UNSET, OptionalNullable +from codat_sync_for_payables.utils.retries import RetryConfig, execute_with_retries + + +class CreateSupplierRequestTypedDict(TypedDict): + """TypedDict variant of CreateSupplierRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + idempotency_key: NotRequired[Annotated[Optional[str], Field(description="A unique identifier to ensure idempotent behaviour for subsequent requests.")]] + supplier_prototype: NotRequired[Optional[SupplierPrototype]] + + +class CreateSupplierRequest(BaseModel): + """Request envelope for create_supplier.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + idempotency_key: Annotated[Optional[str], Field(description="A unique identifier to ensure idempotent behaviour for subsequent requests.")] = None + supplier_prototype: Optional[SupplierPrototype] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class ListSuppliersRequestTypedDict(TypedDict): + """TypedDict variant of ListSuppliersRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + continuation_token: NotRequired[Annotated[Optional[str], Field(description="Retrieve the next page of results using the continuation token from the previous response.")]] + query: NotRequired[Annotated[Optional[str], Field(description="Codat query string allows you to filter by `sourceModifiedDate` or if a supplier is `Active` or `Archived` in the accounting software. Learn more about Codat's query string [here](https://docs.codat.io/using-the-api/querying).")]] + + +class ListSuppliersRequest(BaseModel): + """Request envelope for list_suppliers.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + continuation_token: Annotated[Optional[str], Field(description="Retrieve the next page of results using the continuation token from the previous response.")] = None + query: Annotated[Optional[str], Field(description="Codat query string allows you to filter by `sourceModifiedDate` or if a supplier is `Active` or `Archived` in the accounting software. Learn more about Codat's query string [here](https://docs.codat.io/using-the-api/querying).")] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class UpdateSupplierRequestTypedDict(TypedDict): + """TypedDict variant of UpdateSupplierRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + supplier_id: Annotated[str, Field(description="Unique identifier for a supplier.")] + supplier_prototype: NotRequired[Optional[SupplierPrototype]] + + +class UpdateSupplierRequest(BaseModel): + """Request envelope for update_supplier.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + supplier_id: Annotated[str, Field(description="Unique identifier for a supplier.")] + supplier_prototype: Optional[SupplierPrototype] = None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + +class Suppliers: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call(config={"arbitrary_types_allowed": True}) + def create( + self, + *, + request: Union['CreateSupplierRequest', 'CreateSupplierRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Supplier: + """Create supplier""" # noqa: E501 + + if isinstance(request, dict): + request = CreateSupplierRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._create_supplier_serialize( + company_id=request.company_id, + connection_id=request.connection_id, + idempotency_key=request.idempotency_key, + supplier_prototype=request.supplier_prototype, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "Supplier", + '400': "ErrorMessage", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='create-supplier', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def create_async( + self, + *, + request: Union['CreateSupplierRequest', 'CreateSupplierRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Supplier: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.create( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _create_supplier_serialize( + self, + company_id, + connection_id, + idempotency_key, + supplier_prototype, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + if connection_id is not None: + _path_params['connectionId'] = connection_id + # process the query parameters + # process the header parameters + if idempotency_key is not None: + _header_params['Idempotency-Key'] = idempotency_key + # process the form parameters + # process the body parameter + if supplier_prototype is not None: + _body_params = supplier_prototype + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/companies/{companyId}/connections/{connectionId}/payables/suppliers', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def list( + self, + *, + request: Union['ListSuppliersRequest', 'ListSuppliersRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Suppliers: + """List suppliers""" # noqa: E501 + + if isinstance(request, dict): + request = ListSuppliersRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._list_suppliers_serialize( + company_id=request.company_id, + connection_id=request.connection_id, + continuation_token=request.continuation_token, + query=request.query, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Suppliers", + '400': "ErrorMessage", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '409': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='list-suppliers', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def list_async( + self, + *, + request: Union['ListSuppliersRequest', 'ListSuppliersRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Suppliers: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.list( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _list_suppliers_serialize( + self, + company_id, + connection_id, + continuation_token, + query, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + if connection_id is not None: + _path_params['connectionId'] = connection_id + # process the query parameters + if continuation_token is not None: + + _query_params.append(('continuationToken', continuation_token)) + + if query is not None: + + _query_params.append(('query', query)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/companies/{companyId}/connections/{connectionId}/payables/suppliers', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def update( + self, + *, + request: Union['UpdateSupplierRequest', 'UpdateSupplierRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Supplier: + """Update supplier""" # noqa: E501 + + if isinstance(request, dict): + request = UpdateSupplierRequest.model_validate(request) + + _effective_timeout_ms = timeout_ms if timeout_ms is not None else getattr(self, "_sdk_timeout_ms", None) + _timeout_s = (_effective_timeout_ms / 1000.0) if _effective_timeout_ms is not None else None + _request_timeout = (_timeout_s, _timeout_s) if _timeout_s is not None else None + _server_override_token = None + if server_url is not None: + _server_override_token = self.api_client.configuration.host + self.api_client.configuration.host = server_url + try: + _param = self._update_supplier_serialize( + company_id=request.company_id, + connection_id=request.connection_id, + supplier_id=request.supplier_id, + supplier_prototype=request.supplier_prototype, + _request_auth=None, + _content_type=None, + _headers=dict(http_headers) if http_headers else None, + _host_index=0, + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Supplier", + '400': "ErrorMessage", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '429': "ErrorMessage", + '500': "ErrorMessage", + '503': "ErrorMessage", + } + finally: + if _server_override_token is not None: + self.api_client.configuration.host = _server_override_token + + _effective_retries = retries if not isinstance(retries, type(UNSET)) else getattr(self, "_sdk_retry_config", None) + if isinstance(_effective_retries, type(UNSET)): + _effective_retries = None + + def _do_call(): + try: + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout, + operation_id='update-supplier', + ) + response_data.read() + _result = self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + # Speakeasy raises SDKError for any status the operation does not document, + # including an unexpected 2xx; OAG's response_deserialize would instead return + # None. Match Speakeasy: if neither the exact status nor its NXX wildcard is + # documented, raise. A documented no-content status is a key mapping to None, + # so it stays and returns None. + _ok_status = getattr(response_data, "status", None) + if (str(_ok_status) not in _response_types_map + and f"{str(_ok_status)[0]}XX" not in _response_types_map): + _ok_body = getattr(response_data, "data", b"") or b"" + raise SDKError( + "Unexpected response received", + raw_response=response_data, + status_code=_ok_status, + body=_ok_body.decode("utf-8", "replace") if isinstance(_ok_body, (bytes, bytearray)) else str(_ok_body), + headers=dict(response_data.getheaders() or {}), + ) + return _result.data + except ApiException as _e: + _body = getattr(_e, "body", "") or "" + _status = getattr(_e, "status", 0) or 0 + _headers = dict(getattr(_e, "headers", None) or {}) + # Raise the typed Codat ErrorMessage only for the statuses this operation + # documents as ErrorMessage, matching Speakeasy (which raises SDKError for any + # undocumented status). Consumers can then do + # `except errors.ErrorMessage as e: e.data.correlation_id`. + if _response_types_map.get(str(_status)) == "ErrorMessage" and _body: + try: + _err_data = _ErrorMessageDataSchema.model_validate_json(_body) + except Exception: + _err_data = None + if _err_data is not None: + raise ErrorMessage( + data=_err_data, + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + raise SDKError( + message=getattr(_e, "reason", None) or str(_e), + status_code=_status, + body=_body, + headers=_headers, + raw_response=_e, + ) from _e + + return execute_with_retries(_do_call, _effective_retries) + + + @validate_call(config={"arbitrary_types_allowed": True}) + async def update_async( + self, + *, + request: Union['UpdateSupplierRequest', 'UpdateSupplierRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Supplier: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.update( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _update_supplier_serialize( + self, + company_id, + connection_id, + supplier_id, + supplier_prototype, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if company_id is not None: + _path_params['companyId'] = company_id + if connection_id is not None: + _path_params['connectionId'] = connection_id + if supplier_id is not None: + _path_params['supplierId'] = supplier_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if supplier_prototype is not None: + _body_params = supplier_prototype + + + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + _auth_settings: List[str] = [ + 'auth_header' + ] + + return self.api_client.param_serialize( + method='PUT', + resource_path='/companies/{companyId}/connections/{connectionId}/payables/suppliers/{supplierId}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/sync-for-payables/src/codat_sync_for_payables/api_client.py b/sync-for-payables/src/codat_sync_for_payables/api_client.py new file mode 100644 index 000000000..3bdd69cde --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/api_client.py @@ -0,0 +1,803 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import datetime +from dateutil.parser import parse +from enum import Enum +import decimal +import json +import mimetypes +import os +import re +import tempfile + +from urllib.parse import quote +from typing import Tuple, Optional, List, Dict, Union +from pydantic import SecretStr + +from codat_sync_for_payables.configuration import Configuration +from codat_sync_for_payables.api_response import ApiResponse, T as ApiResponseT +import codat_sync_for_payables.models +from codat_sync_for_payables import rest +from codat_sync_for_payables.exceptions import ( + ApiValueError, + ApiException, + BadRequestException, + UnauthorizedException, + ForbiddenException, + NotFoundException, + ServiceException +) + +RequestSerialized = Tuple[str, str, Dict[str, str], Optional[str], List[str]] + +class ApiClient: + """Generic API client for OpenAPI client library builds. + + OpenAPI generic API client. This client handles the client- + server communication, and is invariant across implementations. Specifics of + the methods and models for each application are generated from the OpenAPI + templates. + + :param configuration: .Configuration object for this client + :param header_name: a header to pass when making calls to the API. + :param header_value: a header value to pass when making calls to + the API. + :param cookie: a cookie to include in the header when making calls + to the API + """ + + PRIMITIVE_TYPES = (float, bool, bytes, str, int) + NATIVE_TYPES_MAPPING = { + 'int': int, + 'long': int, # TODO remove as only py3 is supported? + 'float': float, + 'str': str, + 'bool': bool, + 'date': datetime.date, + 'datetime': datetime.datetime, + 'decimal': decimal.Decimal, + 'object': object, + } + _pool = None + + def __init__( + self, + configuration=None, + header_name=None, + header_value=None, + cookie=None + ) -> None: + # use default configuration if none is provided + if configuration is None: + configuration = Configuration.get_default() + self.configuration = configuration + + self.rest_client = rest.RESTClientObject(configuration) + self.default_headers = {} + if header_name is not None: + self.default_headers[header_name] = header_value + self.cookie = cookie + # Set default User-Agent. + self.user_agent = 'OpenAPI-Generator/1.0.0/python' + self.client_side_validation = configuration.client_side_validation + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + pass + + @property + def user_agent(self): + """User agent for this API client""" + return self.default_headers['User-Agent'] + + @user_agent.setter + def user_agent(self, value): + self.default_headers['User-Agent'] = value + + def set_default_header(self, header_name, header_value): + self.default_headers[header_name] = header_value + + + _default = None + + @classmethod + def get_default(cls): + """Return new instance of ApiClient. + + This method returns newly created, based on default constructor, + object of ApiClient class or returns a copy of default + ApiClient. + + :return: The ApiClient object. + """ + if cls._default is None: + cls._default = ApiClient() + return cls._default + + @classmethod + def set_default(cls, default): + """Set default instance of ApiClient. + + It stores default ApiClient. + + :param default: object of ApiClient. + """ + cls._default = default + + def param_serialize( + self, + method, + resource_path, + path_params=None, + query_params=None, + header_params=None, + body=None, + post_params=None, + files=None, auth_settings=None, + collection_formats=None, + _host=None, + _request_auth=None + ) -> RequestSerialized: + + """Builds the HTTP request params needed by the request. + :param method: Method to call. + :param resource_path: Path to method endpoint. + :param path_params: Path parameters in the url. + :param query_params: Query parameters in the url. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param auth_settings list: Auth Settings names for the request. + :param files dict: key -> filename, value -> filepath, + for `multipart/form-data`. + :param collection_formats: dict of collection formats for path, query, + header, and post parameters. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :return: tuple of form (path, http_method, query_params, header_params, + body, post_params, files) + """ + + config = self.configuration + + # header parameters + header_params = header_params or {} + header_params.update(self.default_headers) + if self.cookie: + header_params['Cookie'] = self.cookie + if header_params: + header_params = self.sanitize_for_serialization(header_params) + header_params = dict( + self.parameters_to_tuples(header_params,collection_formats) + ) + + # path parameters + if path_params: + path_params = self.sanitize_for_serialization(path_params) + path_params = self.parameters_to_tuples( + path_params, + collection_formats + ) + for k, v in path_params: + # specified safe chars, encode everything + resource_path = resource_path.replace( + '{%s}' % k, + quote(str(v), safe=config.safe_chars_for_path_param) + ) + + # post parameters + if post_params or files: + post_params = post_params if post_params else [] + post_params = self.sanitize_for_serialization(post_params) + post_params = self.parameters_to_tuples( + post_params, + collection_formats + ) + if files: + post_params.extend(self.files_parameters(files)) + + # auth setting + self.update_params_for_auth( + header_params, + query_params, + auth_settings, + resource_path, + method, + body, + request_auth=_request_auth + ) + + # body + if body: + body = self.sanitize_for_serialization(body) + + # request url + if _host is None or self.configuration.ignore_operation_servers: + url = self.configuration.host + resource_path + else: + # use server/host defined in path or operation instead + url = _host + resource_path + + # query parameters + if query_params: + query_params = self.sanitize_for_serialization(query_params) + url_query = self.parameters_to_url_query( + query_params, + collection_formats + ) + url += "?" + url_query + + return method, url, header_params, body, post_params + + + def call_api( + self, + method, + url, + header_params=None, + body=None, + post_params=None, + _request_timeout=None, + operation_id=None, + ) -> rest.RESTResponse: + """Makes the HTTP request (synchronous) + :param method: Method to call. + :param url: Path to method endpoint. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param _request_timeout: timeout setting for this request. + :return: RESTResponse + """ + + try: + # perform request and return response + response_data = self.rest_client.request( + method, url, + headers=header_params, + body=body, post_params=post_params, + _request_timeout=_request_timeout + ) + + except ApiException as e: + raise e + + return response_data + + def response_deserialize( + self, + response_data: rest.RESTResponse, + response_types_map: Optional[Dict[str, ApiResponseT]]=None + ) -> ApiResponse[ApiResponseT]: + """Deserializes response into an object. + :param response_data: RESTResponse object to be deserialized. + :param response_types_map: dict of response types. + :return: ApiResponse + """ + + msg = "RESTResponse.read() must be called before passing it to response_deserialize()" + assert response_data.data is not None, msg + + response_type = response_types_map.get(str(response_data.status), None) + if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599: + # if not found, look for '1XX', '2XX', etc. + response_type = response_types_map.get(str(response_data.status)[0] + "XX", None) + + # deserialize response data + response_text = None + return_data = None + try: + if response_type == "bytearray": + return_data = response_data.data + elif response_type == "file": + return_data = self.__deserialize_file(response_data) + elif response_type is not None: + match = None + content_type = response_data.getheader('content-type') + if content_type is not None: + match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type) + encoding = match.group(1) if match else "utf-8" + response_text = response_data.data.decode(encoding) + return_data = self.deserialize(response_text, response_type, content_type) + finally: + if not 200 <= response_data.status <= 299: + raise ApiException.from_response( + http_resp=response_data, + body=response_text, + data=return_data, + ) + + return ApiResponse( + status_code = response_data.status, + data = return_data, + headers = response_data.getheaders(), + raw_data = response_data.data + ) + + def sanitize_for_serialization(self, obj): + """Builds a JSON POST object. + + If obj is None, return None. + If obj is SecretStr, return obj.get_secret_value() + If obj is str, int, long, float, bool, return directly. + If obj is datetime.datetime, datetime.date + convert to string in iso8601 format. + If obj is decimal.Decimal return string representation. + If obj is list, sanitize each element in the list. + If obj is dict, return the dict. + If obj is OpenAPI model, return the properties dict. + + :param obj: The data to serialize. + :return: The serialized form of data. + """ + if obj is None: + return None + elif isinstance(obj, Enum): + return obj.value + elif isinstance(obj, SecretStr): + return obj.get_secret_value() + elif isinstance(obj, self.PRIMITIVE_TYPES): + return obj + elif isinstance(obj, list): + return [ + self.sanitize_for_serialization(sub_obj) for sub_obj in obj + ] + elif isinstance(obj, tuple): + return tuple( + self.sanitize_for_serialization(sub_obj) for sub_obj in obj + ) + elif isinstance(obj, (datetime.datetime, datetime.date)): + return obj.isoformat() + elif isinstance(obj, decimal.Decimal): + return str(obj) + + elif isinstance(obj, dict): + obj_dict = obj + else: + # Convert model obj to dict except + # attributes `openapi_types`, `attribute_map` + # and attributes which value is not None. + # Convert attribute name to json key in + # model definition for request. + if hasattr(obj, 'to_dict') and callable(getattr(obj, 'to_dict')): + obj_dict = obj.to_dict() + else: + obj_dict = obj.__dict__ + + return { + key: self.sanitize_for_serialization(val) + for key, val in obj_dict.items() + } + + def deserialize(self, response_text: str, response_type: str, content_type: Optional[str]): + """Deserializes response into an object. + + :param response: RESTResponse object to be deserialized. + :param response_type: class literal for + deserialized object, or string of class name. + :param content_type: content type of response. + + :return: deserialized object. + """ + + # fetch data from response object + if content_type is None: + try: + data = json.loads(response_text) + except ValueError: + data = response_text + elif re.match(r'^application/(json|[\w!#$&.+-^_]+\+json)\s*(;|$)', content_type, re.IGNORECASE): + if response_text == "": + data = "" + else: + data = json.loads(response_text) + elif re.match(r'^text\/[a-z.+-]+\s*(;|$)', content_type, re.IGNORECASE): + data = response_text + else: + raise ApiException( + status=0, + reason="Unsupported content type: {0}".format(content_type) + ) + + return self.__deserialize(data, response_type) + + def __deserialize(self, data, klass): + """Deserializes dict, list, str into an object. + + :param data: dict, list or str. + :param klass: class literal, or string of class name. + + :return: object. + """ + if data is None: + return None + + if isinstance(klass, str): + if klass.startswith('List['): + m = re.match(r'List\[(.*)]', klass) + assert m is not None, "Malformed List type definition" + sub_kls = m.group(1) + return [self.__deserialize(sub_data, sub_kls) + for sub_data in data] + + if klass.startswith('Dict['): + m = re.match(r'Dict\[([^,]*), (.*)]', klass) + assert m is not None, "Malformed Dict type definition" + sub_kls = m.group(2) + return {k: self.__deserialize(v, sub_kls) + for k, v in data.items()} + + # convert str to class + if klass in self.NATIVE_TYPES_MAPPING: + klass = self.NATIVE_TYPES_MAPPING[klass] + else: + klass = getattr(codat_sync_for_payables.models, klass) + + if klass in self.PRIMITIVE_TYPES: + return self.__deserialize_primitive(data, klass) + elif klass == object: + return self.__deserialize_object(data) + elif klass == datetime.date: + return self.__deserialize_date(data) + elif klass == datetime.datetime: + return self.__deserialize_datetime(data) + elif klass == decimal.Decimal: + return decimal.Decimal(data) + elif issubclass(klass, Enum): + return self.__deserialize_enum(data, klass) + else: + return self.__deserialize_model(data, klass) + + def parameters_to_tuples(self, params, collection_formats): + """Get parameters as list of tuples, formatting collections. + + :param params: Parameters as dict or list of two-tuples + :param dict collection_formats: Parameter collection formats + :return: Parameters as list of tuples, collections formatted + """ + new_params: List[Tuple[str, str]] = [] + if collection_formats is None: + collection_formats = {} + for k, v in params.items() if isinstance(params, dict) else params: + if k in collection_formats: + collection_format = collection_formats[k] + if collection_format == 'multi': + new_params.extend((k, value) for value in v) + else: + if collection_format == 'ssv': + delimiter = ' ' + elif collection_format == 'tsv': + delimiter = '\t' + elif collection_format == 'pipes': + delimiter = '|' + else: # csv is the default + delimiter = ',' + new_params.append( + (k, delimiter.join(str(value) for value in v))) + else: + new_params.append((k, v)) + return new_params + + def parameters_to_url_query(self, params, collection_formats): + """Get parameters as list of tuples, formatting collections. + + :param params: Parameters as dict or list of two-tuples + :param dict collection_formats: Parameter collection formats + :return: URL query string (e.g. a=Hello%20World&b=123) + """ + new_params: List[Tuple[str, str]] = [] + if collection_formats is None: + collection_formats = {} + for k, v in params.items() if isinstance(params, dict) else params: + if isinstance(v, bool): + v = str(v).lower() + if isinstance(v, (int, float)): + v = str(v) + if isinstance(v, dict): + v = json.dumps(v) + + if k in collection_formats: + collection_format = collection_formats[k] + if collection_format == 'multi': + new_params.extend((k, str(value)) for value in v) + else: + if collection_format == 'ssv': + delimiter = ' ' + elif collection_format == 'tsv': + delimiter = '\t' + elif collection_format == 'pipes': + delimiter = '|' + else: # csv is the default + delimiter = ',' + new_params.append( + (k, delimiter.join(quote(str(value)) for value in v)) + ) + else: + new_params.append((k, quote(str(v)))) + + return "&".join(["=".join(map(str, item)) for item in new_params]) + + def files_parameters( + self, + files: Dict[str, Union[str, bytes, List[str], List[bytes], Tuple[str, bytes]]], + ): + """Builds form parameters. + + :param files: File parameters. + :return: Form parameters with files. + """ + params = [] + for k, v in files.items(): + mimetype = None + if isinstance(v, str): + with open(v, 'rb') as f: + filename = os.path.basename(f.name) + filedata = f.read() + elif isinstance(v, bytes): + filename = k + filedata = v + elif isinstance(v, tuple): + if len(v) == 3: + filename, filedata, mimetype = v + else: + filename, filedata = v + elif isinstance(v, list): + for file_param in v: + params.extend(self.files_parameters({k: file_param})) + continue + else: + raise ValueError("Unsupported file value") + mimetype = mimetype or ( + mimetypes.guess_type(filename)[0] + or 'application/octet-stream' + ) + params.append( + tuple([k, tuple([filename, filedata, mimetype])]) + ) + return params + + def select_header_accept(self, accepts: List[str]) -> Optional[str]: + """Returns `Accept` based on an array of accepts provided. + + :param accepts: List of headers. + :return: Accept (e.g. application/json). + """ + if not accepts: + return None + + for accept in accepts: + if re.search('json', accept, re.IGNORECASE): + return accept + + return accepts[0] + + def select_header_content_type(self, content_types): + """Returns `Content-Type` based on an array of content_types provided. + + :param content_types: List of content-types. + :return: Content-Type (e.g. application/json). + """ + if not content_types: + return None + + for content_type in content_types: + if re.search('json', content_type, re.IGNORECASE): + return content_type + + return content_types[0] + + def update_params_for_auth( + self, + headers, + queries, + auth_settings, + resource_path, + method, + body, + request_auth=None + ) -> None: + """Updates header and query params based on authentication setting. + + :param headers: Header parameters dict to be updated. + :param queries: Query parameters tuple list to be updated. + :param auth_settings: Authentication setting identifiers list. + :resource_path: A string representation of the HTTP request resource path. + :method: A string representation of the HTTP request method. + :body: A object representing the body of the HTTP request. + The object type is the return value of sanitize_for_serialization(). + :param request_auth: if set, the provided settings will + override the token in the configuration. + """ + if not auth_settings: + return + + if request_auth: + self._apply_auth_params( + headers, + queries, + resource_path, + method, + body, + request_auth + ) + else: + for auth in auth_settings: + auth_setting = self.configuration.auth_settings().get(auth) + if auth_setting: + self._apply_auth_params( + headers, + queries, + resource_path, + method, + body, + auth_setting + ) + + def _apply_auth_params( + self, + headers, + queries, + resource_path, + method, + body, + auth_setting + ) -> None: + """Updates the request parameters based on a single auth_setting + + :param headers: Header parameters dict to be updated. + :param queries: Query parameters tuple list to be updated. + :resource_path: A string representation of the HTTP request resource path. + :method: A string representation of the HTTP request method. + :body: A object representing the body of the HTTP request. + The object type is the return value of sanitize_for_serialization(). + :param auth_setting: auth settings for the endpoint + """ + if auth_setting['in'] == 'cookie': + headers['Cookie'] = auth_setting['value'] + elif auth_setting['in'] == 'header': + if auth_setting['type'] != 'http-signature': + headers[auth_setting['key']] = auth_setting['value'] + elif auth_setting['in'] == 'query': + queries.append((auth_setting['key'], auth_setting['value'])) + else: + raise ApiValueError( + 'Authentication token must be in `query` or `header`' + ) + + def __deserialize_file(self, response): + """Deserializes body to file + + Saves response body into a file in a temporary folder, + using the filename from the `Content-Disposition` header if provided. + + handle file downloading + save response body into a tmp file and return the instance + + :param response: RESTResponse. + :return: file path. + """ + fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path) + os.close(fd) + os.remove(path) + + content_disposition = response.getheader("Content-Disposition") + if content_disposition: + m = re.search( + r'filename=[\'"]?([^\'"\s]+)[\'"]?', + content_disposition + ) + assert m is not None, "Unexpected 'content-disposition' header value" + filename = m.group(1) + path = os.path.join(os.path.dirname(path), filename) + + with open(path, "wb") as f: + f.write(response.data) + + return path + + def __deserialize_primitive(self, data, klass): + """Deserializes string to primitive type. + + :param data: str. + :param klass: class literal. + + :return: int, long, float, str, bool. + """ + try: + return klass(data) + except UnicodeEncodeError: + return str(data) + except TypeError: + return data + + def __deserialize_object(self, value): + """Return an original value. + + :return: object. + """ + return value + + def __deserialize_date(self, string): + """Deserializes string to date. + + :param string: str. + :return: date. + """ + try: + return parse(string).date() + except ImportError: + return string + except ValueError: + raise rest.ApiException( + status=0, + reason="Failed to parse `{0}` as date object".format(string) + ) + + def __deserialize_datetime(self, string): + """Deserializes string to datetime. + + The string should be in iso8601 datetime format. + + :param string: str. + :return: datetime. + """ + try: + return parse(string) + except ImportError: + return string + except ValueError: + raise rest.ApiException( + status=0, + reason=( + "Failed to parse `{0}` as datetime object" + .format(string) + ) + ) + + def __deserialize_enum(self, data, klass): + """Deserializes primitive type to enum. + + :param data: primitive type. + :param klass: class literal. + :return: enum value. + """ + try: + return klass(data) + except ValueError: + raise rest.ApiException( + status=0, + reason=( + "Failed to parse `{0}` as `{1}`" + .format(data, klass) + ) + ) + + def __deserialize_model(self, data, klass): + """Deserializes list or dict to model. + + :param data: dict, list. + :param klass: class literal. + :return: model object. + """ + + return klass.from_dict(data) diff --git a/sync-for-payables/src/codat_sync_for_payables/api_response.py b/sync-for-payables/src/codat_sync_for_payables/api_response.py new file mode 100644 index 000000000..8a1236a62 --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/api_response.py @@ -0,0 +1,21 @@ +"""API response object.""" + +from __future__ import annotations +from typing import Optional, Generic, Mapping, TypeVar +from pydantic import Field, BaseModel + +T = TypeVar("T") + +class ApiResponse(BaseModel, Generic[T]): + """ + API response object + """ + + status_code: int = Field(description="HTTP status code") + headers: Optional[Mapping[str, str]] = Field(None, description="HTTP headers") + data: T = Field(description="Deserialized data given the data type") + raw_data: bytes = Field(description="Raw data (HTTP response body)") + + model_config = { + "arbitrary_types_allowed": True + } diff --git a/sync-for-payables/src/codat_sync_for_payables/bank_accounts.py b/sync-for-payables/src/codat_sync_for_payables/bank_accounts.py index d7e2d6488..ad903d05e 100644 --- a/sync-for-payables/src/codat_sync_for_payables/bank_accounts.py +++ b/sync-for-payables/src/codat_sync_for_payables/bank_accounts.py @@ -1,229 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.bank_accounts — re-export of the bank_accounts method group.""" -from .basesdk import BaseSDK -from codat_sync_for_payables import utils -from codat_sync_for_payables._hooks import HookContext -from codat_sync_for_payables.models import errors, operations, shared -from codat_sync_for_payables.types import BaseModel, OptionalNullable, UNSET -from codat_sync_for_payables.utils.unmarshal_json_response import ( - unmarshal_json_response, -) -from typing import Any, Mapping, Optional, Union, cast - - -class BankAccounts(BaseSDK): - r"""Create a bank account for a given company's connection.""" - - def create( - self, - *, - request: Union[ - operations.CreateBankAccountRequest, - operations.CreateBankAccountRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.BankAccount: - r"""Create bank account - - The *Create bank account* endpoint creates a new [bank account](https://docs.codat.io/sync-for-payables-api#/schemas/BankAccount) for a given company's connection. - - [Bank accounts](https://docs.codat.io/sync-for-payables-api#/schemas/BankAccount) are financial accounts maintained by a bank or other financial institution. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.CreateBankAccountRequest) - request = cast(operations.CreateBankAccountRequest, request) - - req = self._build_request( - method="POST", - path="/companies/{companyId}/connections/{connectionId}/payables/bankAccounts", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.bank_account_prototype if request is not None else None, - False, - True, - "json", - Optional[shared.BankAccountPrototype], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="create-bank-account", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "201", "application/json"): - return unmarshal_json_response(shared.BankAccount, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def create_async( - self, - *, - request: Union[ - operations.CreateBankAccountRequest, - operations.CreateBankAccountRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.BankAccount: - r"""Create bank account - - The *Create bank account* endpoint creates a new [bank account](https://docs.codat.io/sync-for-payables-api#/schemas/BankAccount) for a given company's connection. - - [Bank accounts](https://docs.codat.io/sync-for-payables-api#/schemas/BankAccount) are financial accounts maintained by a bank or other financial institution. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.CreateBankAccountRequest) - request = cast(operations.CreateBankAccountRequest, request) - - req = self._build_request_async( - method="POST", - path="/companies/{companyId}/connections/{connectionId}/payables/bankAccounts", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.bank_account_prototype if request is not None else None, - False, - True, - "json", - Optional[shared.BankAccountPrototype], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="create-bank-account", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "201", "application/json"): - return unmarshal_json_response(shared.BankAccount, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) +from codat_sync_for_payables.api.bank_accounts import BankAccounts diff --git a/sync-for-payables/src/codat_sync_for_payables/basesdk.py b/sync-for-payables/src/codat_sync_for_payables/basesdk.py deleted file mode 100644 index 3aad08733..000000000 --- a/sync-for-payables/src/codat_sync_for_payables/basesdk.py +++ /dev/null @@ -1,393 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from .sdkconfiguration import SDKConfiguration -from codat_sync_for_payables import utils -from codat_sync_for_payables._hooks import ( - AfterErrorContext, - AfterSuccessContext, - BeforeRequestContext, - HookContext, -) -from codat_sync_for_payables.models import errors -from codat_sync_for_payables.utils import ( - RetryConfig, - SerializedRequestBody, - get_body_content, - run_sync_in_thread, -) -import httpx -from typing import Callable, List, Mapping, Optional, Tuple -from urllib.parse import parse_qs, urlparse - - -class BaseSDK: - sdk_configuration: SDKConfiguration - parent_ref: Optional[object] = None - """ - Reference to the root SDK instance, if any. This will prevent it from - being garbage collected while there are active streams. - """ - - def __init__( - self, - sdk_config: SDKConfiguration, - parent_ref: Optional[object] = None, - ) -> None: - self.sdk_configuration = sdk_config - self.parent_ref = parent_ref - - def _get_url(self, base_url, url_variables): - sdk_url, sdk_variables = self.sdk_configuration.get_server_details() - - if base_url is None: - base_url = sdk_url - - if url_variables is None: - url_variables = sdk_variables - - return utils.template_url(base_url, url_variables) - - def _build_request_async( - self, - method, - path, - base_url, - url_variables, - request, - request_body_required, - request_has_path_params, - request_has_query_params, - user_agent_header, - accept_header_value, - _globals=None, - security=None, - timeout_ms: Optional[int] = None, - get_serialized_body: Optional[ - Callable[[], Optional[SerializedRequestBody]] - ] = None, - url_override: Optional[str] = None, - http_headers: Optional[Mapping[str, str]] = None, - allow_empty_value: Optional[List[str]] = None, - allowed_fields: Optional[List[str]] = None, - ) -> httpx.Request: - client = self.sdk_configuration.async_client - return self._build_request_with_client( - client, - method, - path, - base_url, - url_variables, - request, - request_body_required, - request_has_path_params, - request_has_query_params, - user_agent_header, - accept_header_value, - _globals, - security, - timeout_ms, - get_serialized_body, - url_override, - http_headers, - allow_empty_value, - allowed_fields, - ) - - def _build_request( - self, - method, - path, - base_url, - url_variables, - request, - request_body_required, - request_has_path_params, - request_has_query_params, - user_agent_header, - accept_header_value, - _globals=None, - security=None, - timeout_ms: Optional[int] = None, - get_serialized_body: Optional[ - Callable[[], Optional[SerializedRequestBody]] - ] = None, - url_override: Optional[str] = None, - http_headers: Optional[Mapping[str, str]] = None, - allow_empty_value: Optional[List[str]] = None, - allowed_fields: Optional[List[str]] = None, - ) -> httpx.Request: - client = self.sdk_configuration.client - return self._build_request_with_client( - client, - method, - path, - base_url, - url_variables, - request, - request_body_required, - request_has_path_params, - request_has_query_params, - user_agent_header, - accept_header_value, - _globals, - security, - timeout_ms, - get_serialized_body, - url_override, - http_headers, - allow_empty_value, - allowed_fields, - ) - - def _build_request_with_client( - self, - client, - method, - path, - base_url, - url_variables, - request, - request_body_required, - request_has_path_params, - request_has_query_params, - user_agent_header, - accept_header_value, - _globals=None, - security=None, - timeout_ms: Optional[int] = None, - get_serialized_body: Optional[ - Callable[[], Optional[SerializedRequestBody]] - ] = None, - url_override: Optional[str] = None, - http_headers: Optional[Mapping[str, str]] = None, - allow_empty_value: Optional[List[str]] = None, - allowed_fields: Optional[List[str]] = None, - ) -> httpx.Request: - query_params = {} - - url = url_override - if url is None: - url = utils.generate_url( - self._get_url(base_url, url_variables), - path, - request if request_has_path_params else None, - _globals if request_has_path_params else None, - ) - - query_params = utils.get_query_params( - request if request_has_query_params else None, - _globals if request_has_query_params else None, - allow_empty_value, - ) - else: - # Pick up the query parameter from the override so they can be - # preserved when building the request later on (necessary as of - # httpx 0.28). - parsed_override = urlparse(str(url_override)) - query_params = parse_qs(parsed_override.query, keep_blank_values=True) - - headers = utils.get_headers(request, _globals) - headers["Accept"] = accept_header_value - headers[user_agent_header] = self.sdk_configuration.user_agent - - if security is not None: - if callable(security): - security = security() - - if security is not None: - security_headers, security_query_params = utils.get_security( - security, allowed_fields - ) - headers = {**headers, **security_headers} - query_params = {**query_params, **security_query_params} - - serialized_request_body = SerializedRequestBody() - if get_serialized_body is not None: - rb = get_serialized_body() - if request_body_required and rb is None: - raise ValueError("request body is required") - - if rb is not None: - serialized_request_body = rb - - if ( - serialized_request_body.media_type is not None - and serialized_request_body.media_type - not in ( - "multipart/form-data", - "multipart/mixed", - ) - ): - headers["content-type"] = serialized_request_body.media_type - - if http_headers is not None: - for header, value in http_headers.items(): - headers[header] = value - - timeout = timeout_ms / 1000 if timeout_ms is not None else None - - return client.build_request( - method, - url, - params=query_params, - content=serialized_request_body.content, - data=serialized_request_body.data, - files=serialized_request_body.files, - headers=headers, - timeout=timeout if timeout is not None else httpx.USE_CLIENT_DEFAULT, - ) - - def do_request( - self, - hook_ctx: HookContext, - request: httpx.Request, - is_error_status_code: Callable[[int], bool], - stream: bool = False, - retry_config: Optional[Tuple[RetryConfig, List[str]]] = None, - ) -> httpx.Response: - client = self.sdk_configuration.client - logger = self.sdk_configuration.debug_logger - - hooks = self.sdk_configuration.__dict__["_hooks"] - - def do(): - http_res = None - try: - req = hooks.before_request(BeforeRequestContext(hook_ctx), request) - if "timeout" in request.extensions and "timeout" not in req.extensions: - req.extensions["timeout"] = request.extensions["timeout"] - logger.debug( - "Request:\nMethod: %s\nURL: %s\nHeaders: %s\nBody: %s", - req.method, - req.url, - req.headers, - get_body_content(req), - ) - - if client is None: - raise ValueError("client is required") - - http_res = client.send(req, stream=stream) - except Exception as e: - _, e = hooks.after_error(AfterErrorContext(hook_ctx), None, e) - if e is not None: - logger.debug("Request Exception", exc_info=True) - raise e - - if http_res is None: - logger.debug("Raising no response SDK error") - raise errors.NoResponseError("No response received") - - logger.debug( - "Response:\nStatus Code: %s\nURL: %s\nHeaders: %s\nBody: %s", - http_res.status_code, - http_res.url, - http_res.headers, - "" if stream else http_res.text, - ) - - return http_res - - if retry_config is not None: - http_res = utils.retry(do, utils.Retries(retry_config[0], retry_config[1])) - else: - http_res = do() - - if is_error_status_code(http_res.status_code): - result, err = hooks.after_error(AfterErrorContext(hook_ctx), http_res, None) - if err is not None: - logger.debug("Request Exception", exc_info=True) - raise err - if result is not None: - http_res = result - else: - logger.debug("Raising unexpected SDK error") - raise errors.SDKError("Unexpected error occurred", http_res) - else: - http_res = hooks.after_success(AfterSuccessContext(hook_ctx), http_res) - - return http_res - - async def do_request_async( - self, - hook_ctx: HookContext, - request: httpx.Request, - is_error_status_code: Callable[[int], bool], - stream: bool = False, - retry_config: Optional[Tuple[RetryConfig, List[str]]] = None, - ) -> httpx.Response: - client = self.sdk_configuration.async_client - logger = self.sdk_configuration.debug_logger - - hooks = self.sdk_configuration.__dict__["_hooks"] - - async def do(): - http_res = None - try: - req = await run_sync_in_thread( - hooks.before_request, BeforeRequestContext(hook_ctx), request - ) - - if "timeout" in request.extensions and "timeout" not in req.extensions: - req.extensions["timeout"] = request.extensions["timeout"] - logger.debug( - "Request:\nMethod: %s\nURL: %s\nHeaders: %s\nBody: %s", - req.method, - req.url, - req.headers, - get_body_content(req), - ) - - if client is None: - raise ValueError("client is required") - - http_res = await client.send(req, stream=stream) - except Exception as e: - _, e = await run_sync_in_thread( - hooks.after_error, AfterErrorContext(hook_ctx), None, e - ) - - if e is not None: - logger.debug("Request Exception", exc_info=True) - raise e - - if http_res is None: - logger.debug("Raising no response SDK error") - raise errors.NoResponseError("No response received") - - logger.debug( - "Response:\nStatus Code: %s\nURL: %s\nHeaders: %s\nBody: %s", - http_res.status_code, - http_res.url, - http_res.headers, - "" if stream else http_res.text, - ) - - return http_res - - if retry_config is not None: - http_res = await utils.retry_async( - do, utils.Retries(retry_config[0], retry_config[1]) - ) - else: - http_res = await do() - - if is_error_status_code(http_res.status_code): - result, err = await run_sync_in_thread( - hooks.after_error, AfterErrorContext(hook_ctx), http_res, None - ) - - if err is not None: - logger.debug("Request Exception", exc_info=True) - raise err - if result is not None: - http_res = result - else: - logger.debug("Raising unexpected SDK error") - raise errors.SDKError("Unexpected error occurred", http_res) - else: - http_res = await run_sync_in_thread( - hooks.after_success, AfterSuccessContext(hook_ctx), http_res - ) - - return http_res diff --git a/sync-for-payables/src/codat_sync_for_payables/bill_payments.py b/sync-for-payables/src/codat_sync_for_payables/bill_payments.py index 1c7c0d4ab..46bf49bf9 100644 --- a/sync-for-payables/src/codat_sync_for_payables/bill_payments.py +++ b/sync-for-payables/src/codat_sync_for_payables/bill_payments.py @@ -1,441 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.bill_payments — re-export of the bill_payments method group.""" -from .basesdk import BaseSDK -from codat_sync_for_payables import utils -from codat_sync_for_payables._hooks import HookContext -from codat_sync_for_payables.models import errors, operations, shared -from codat_sync_for_payables.types import BaseModel, OptionalNullable, UNSET -from codat_sync_for_payables.utils.unmarshal_json_response import ( - unmarshal_json_response, -) -from typing import Any, Mapping, Optional, Union, cast - - -class BillPayments(BaseSDK): - r"""Get, create, and update Bill payments.""" - - def get_payment_options( - self, - *, - request: Union[ - operations.GetMappingOptionsPaymentsRequest, - operations.GetMappingOptionsPaymentsRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.PaymentMappingOptions: - r"""Get payment mapping options - - Use the *Get mapping options - Payments* endpoint to return a list of available mapping options for a given company's connection ID. - - By default, this endpoint returns a list of active bank accounts. You can use [querying](https://docs.codat.io/using-the-api/querying) to change that. - - Mapping options are a set of bank accounts used to configure the SMB's payables integration. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal( - request, operations.GetMappingOptionsPaymentsRequest - ) - request = cast(operations.GetMappingOptionsPaymentsRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/connections/{connectionId}/payables/mappingOptions/payments", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-mapping-options-payments", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.PaymentMappingOptions, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def get_payment_options_async( - self, - *, - request: Union[ - operations.GetMappingOptionsPaymentsRequest, - operations.GetMappingOptionsPaymentsRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.PaymentMappingOptions: - r"""Get payment mapping options - - Use the *Get mapping options - Payments* endpoint to return a list of available mapping options for a given company's connection ID. - - By default, this endpoint returns a list of active bank accounts. You can use [querying](https://docs.codat.io/using-the-api/querying) to change that. - - Mapping options are a set of bank accounts used to configure the SMB's payables integration. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal( - request, operations.GetMappingOptionsPaymentsRequest - ) - request = cast(operations.GetMappingOptionsPaymentsRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/connections/{connectionId}/payables/mappingOptions/payments", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-mapping-options-payments", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.PaymentMappingOptions, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def create( - self, - *, - request: Union[ - operations.CreateBillPaymentRequest, - operations.CreateBillPaymentRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.BillPayment: - r"""Create bill payment - - The *Create bill payment* endpoint creates a new [bill payment](https://docs.codat.io/sync-for-payables-api#/schemas/BillPayment) for a given company's connection. - - [Bill payments](https://docs.codat.io/sync-for-payables-api#/schemas/BillPayment) are an allocation of money within any Accounts Payable account. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.CreateBillPaymentRequest) - request = cast(operations.CreateBillPaymentRequest, request) - - req = self._build_request( - method="POST", - path="/companies/{companyId}/connections/{connectionId}/payables/bills/{billId}/payment", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.bill_payment_prototype if request is not None else None, - False, - True, - "json", - Optional[shared.BillPaymentPrototype], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="create-bill-payment", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "201", "application/json"): - return unmarshal_json_response(shared.BillPayment, http_res) - if utils.match_response( - http_res, - ["400", "401", "402", "403", "404", "409", "429"], - "application/json", - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def create_async( - self, - *, - request: Union[ - operations.CreateBillPaymentRequest, - operations.CreateBillPaymentRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.BillPayment: - r"""Create bill payment - - The *Create bill payment* endpoint creates a new [bill payment](https://docs.codat.io/sync-for-payables-api#/schemas/BillPayment) for a given company's connection. - - [Bill payments](https://docs.codat.io/sync-for-payables-api#/schemas/BillPayment) are an allocation of money within any Accounts Payable account. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.CreateBillPaymentRequest) - request = cast(operations.CreateBillPaymentRequest, request) - - req = self._build_request_async( - method="POST", - path="/companies/{companyId}/connections/{connectionId}/payables/bills/{billId}/payment", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.bill_payment_prototype if request is not None else None, - False, - True, - "json", - Optional[shared.BillPaymentPrototype], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="create-bill-payment", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "201", "application/json"): - return unmarshal_json_response(shared.BillPayment, http_res) - if utils.match_response( - http_res, - ["400", "401", "402", "403", "404", "409", "429"], - "application/json", - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) +from codat_sync_for_payables.api.bill_payments import BillPayments diff --git a/sync-for-payables/src/codat_sync_for_payables/bills.py b/sync-for-payables/src/codat_sync_for_payables/bills.py index 472d297c4..ab2d9be5d 100644 --- a/sync-for-payables/src/codat_sync_for_payables/bills.py +++ b/sync-for-payables/src/codat_sync_for_payables/bills.py @@ -1,1514 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.bills — re-export of the bills method group.""" -from .basesdk import BaseSDK -from codat_sync_for_payables import utils -from codat_sync_for_payables._hooks import HookContext -from codat_sync_for_payables.models import errors, operations, shared -from codat_sync_for_payables.types import BaseModel, OptionalNullable, UNSET -from codat_sync_for_payables.utils.unmarshal_json_response import ( - unmarshal_json_response, -) -import httpx -from typing import Any, List, Mapping, Optional, Union, cast - - -class Bills(BaseSDK): - r"""Get, create, and update Bills.""" - - def get_bill_options( - self, - *, - request: Union[ - operations.GetMappingOptionsBillsRequest, - operations.GetMappingOptionsBillsRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.BillMappingOptions: - r"""Get bill mapping options - - Use the *Get mapping options - Bills* endpoint to return a list of available mapping options for a given company's connection ID. - - By default, this endpoint returns a list of active accounts and tax rates. You can use [querying](https://docs.codat.io/using-the-api/querying) to change that. - - Mapping options are a set of accounts and tax rates used to configure the SMB's payables integration. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.GetMappingOptionsBillsRequest) - request = cast(operations.GetMappingOptionsBillsRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/connections/{connectionId}/payables/mappingOptions/bills", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-mapping-options-bills", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.BillMappingOptions, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def get_bill_options_async( - self, - *, - request: Union[ - operations.GetMappingOptionsBillsRequest, - operations.GetMappingOptionsBillsRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.BillMappingOptions: - r"""Get bill mapping options - - Use the *Get mapping options - Bills* endpoint to return a list of available mapping options for a given company's connection ID. - - By default, this endpoint returns a list of active accounts and tax rates. You can use [querying](https://docs.codat.io/using-the-api/querying) to change that. - - Mapping options are a set of accounts and tax rates used to configure the SMB's payables integration. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.GetMappingOptionsBillsRequest) - request = cast(operations.GetMappingOptionsBillsRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/connections/{connectionId}/payables/mappingOptions/bills", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-mapping-options-bills", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.BillMappingOptions, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def list( - self, - *, - request: Union[ - operations.ListBillsRequest, operations.ListBillsRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Bills: - r"""List bills - - The *List bills* endpoint returns a list of [bills](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) for a given company's connection. - - [Bills](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) are invoices that represent the SMB's financial obligations to their supplier for a purchase of goods or services. - - By default, the endpoint will return all bills with a status of 'Open' & 'PartiallyPaid' to show all oustanding bills. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.ListBillsRequest) - request = cast(operations.ListBillsRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/connections/{connectionId}/payables/bills", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="list-bills", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Bills, http_res) - if utils.match_response( - http_res, - ["400", "401", "402", "403", "404", "409", "429"], - "application/json", - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def list_async( - self, - *, - request: Union[ - operations.ListBillsRequest, operations.ListBillsRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Bills: - r"""List bills - - The *List bills* endpoint returns a list of [bills](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) for a given company's connection. - - [Bills](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) are invoices that represent the SMB's financial obligations to their supplier for a purchase of goods or services. - - By default, the endpoint will return all bills with a status of 'Open' & 'PartiallyPaid' to show all oustanding bills. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.ListBillsRequest) - request = cast(operations.ListBillsRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/connections/{connectionId}/payables/bills", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="list-bills", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Bills, http_res) - if utils.match_response( - http_res, - ["400", "401", "402", "403", "404", "409", "429"], - "application/json", - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def create( - self, - *, - request: Union[ - operations.CreateBillRequest, operations.CreateBillRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Bill: - r"""Create bill - - The *Create bill* endpoint creates a new [bill](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) for a given company's connection. - - [Bills](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) are invoices that represent the SMB's financial obligations to their supplier for a purchase of goods or services. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.CreateBillRequest) - request = cast(operations.CreateBillRequest, request) - - req = self._build_request( - method="POST", - path="/companies/{companyId}/connections/{connectionId}/payables/bills", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.bill_prototype if request is not None else None, - False, - True, - "json", - Optional[shared.BillPrototype], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="create-bill", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "201", "application/json"): - return unmarshal_json_response(shared.Bill, http_res) - if utils.match_response( - http_res, - ["400", "401", "402", "403", "404", "409", "429"], - "application/json", - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def create_async( - self, - *, - request: Union[ - operations.CreateBillRequest, operations.CreateBillRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Bill: - r"""Create bill - - The *Create bill* endpoint creates a new [bill](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) for a given company's connection. - - [Bills](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) are invoices that represent the SMB's financial obligations to their supplier for a purchase of goods or services. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.CreateBillRequest) - request = cast(operations.CreateBillRequest, request) - - req = self._build_request_async( - method="POST", - path="/companies/{companyId}/connections/{connectionId}/payables/bills", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.bill_prototype if request is not None else None, - False, - True, - "json", - Optional[shared.BillPrototype], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="create-bill", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "201", "application/json"): - return unmarshal_json_response(shared.Bill, http_res) - if utils.match_response( - http_res, - ["400", "401", "402", "403", "404", "409", "429"], - "application/json", - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def update( - self, - *, - request: Union[ - operations.UpdateBillRequest, operations.UpdateBillRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Bill: - r"""Update bill - - The *Update bill* endpoint updates an existing [bill](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) for a given company's connection. - - [Bills](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) are invoices that represent the SMB's financial obligations to their supplier for a purchase of goods or services. - - ### Supported Integrations - - | Integration | Supported | - |-------------------------------|-----------| - | FreeAgent | Yes | - | QuickBooks Online | Yes | - | Xero | Yes | - | Oracle NetSuite | No | - | Sage Intacct | No | - | Zoho Books | No | - - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.UpdateBillRequest) - request = cast(operations.UpdateBillRequest, request) - - req = self._build_request( - method="PUT", - path="/companies/{companyId}/connections/{connectionId}/payables/bills/{billId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.bill_prototype if request is not None else None, - False, - True, - "json", - Optional[shared.BillPrototype], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="update-bill", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Bill, http_res) - if utils.match_response( - http_res, - ["400", "401", "402", "403", "404", "409", "429"], - "application/json", - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def update_async( - self, - *, - request: Union[ - operations.UpdateBillRequest, operations.UpdateBillRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Bill: - r"""Update bill - - The *Update bill* endpoint updates an existing [bill](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) for a given company's connection. - - [Bills](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) are invoices that represent the SMB's financial obligations to their supplier for a purchase of goods or services. - - ### Supported Integrations - - | Integration | Supported | - |-------------------------------|-----------| - | FreeAgent | Yes | - | QuickBooks Online | Yes | - | Xero | Yes | - | Oracle NetSuite | No | - | Sage Intacct | No | - | Zoho Books | No | - - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.UpdateBillRequest) - request = cast(operations.UpdateBillRequest, request) - - req = self._build_request_async( - method="PUT", - path="/companies/{companyId}/connections/{connectionId}/payables/bills/{billId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.bill_prototype if request is not None else None, - False, - True, - "json", - Optional[shared.BillPrototype], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="update-bill", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Bill, http_res) - if utils.match_response( - http_res, - ["400", "401", "402", "403", "404", "409", "429"], - "application/json", - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def upload_attachment( - self, - *, - request: Union[ - operations.UploadBillAttachmentRequest, - operations.UploadBillAttachmentRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Attachment: - r"""Upload bill attachment - - The *Upload bill attachment* endpoint uploads an attachment and assigns it against a specific `billId`. - - [Bills](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) are invoices that represent the SMB's financial obligations to their supplier for a purchase of goods or services. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.UploadBillAttachmentRequest) - request = cast(operations.UploadBillAttachmentRequest, request) - - req = self._build_request( - method="POST", - path="/companies/{companyId}/connections/{connectionId}/payables/bills/{billId}/attachments", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.attachment_upload if request is not None else None, - False, - True, - "multipart", - Optional[shared.AttachmentUpload], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="upload-bill-attachment", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "201", "application/json"): - return unmarshal_json_response(shared.Attachment, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def upload_attachment_async( - self, - *, - request: Union[ - operations.UploadBillAttachmentRequest, - operations.UploadBillAttachmentRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Attachment: - r"""Upload bill attachment - - The *Upload bill attachment* endpoint uploads an attachment and assigns it against a specific `billId`. - - [Bills](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) are invoices that represent the SMB's financial obligations to their supplier for a purchase of goods or services. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.UploadBillAttachmentRequest) - request = cast(operations.UploadBillAttachmentRequest, request) - - req = self._build_request_async( - method="POST", - path="/companies/{companyId}/connections/{connectionId}/payables/bills/{billId}/attachments", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.attachment_upload if request is not None else None, - False, - True, - "multipart", - Optional[shared.AttachmentUpload], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="upload-bill-attachment", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "201", "application/json"): - return unmarshal_json_response(shared.Attachment, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def list_attachments( - self, - *, - request: Union[ - operations.ListBillAttachmentsRequest, - operations.ListBillAttachmentsRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> List[shared.Attachment]: - r"""List bill attachments - - The *List bill attachments* endpoint returns a list of attachments available to download for a given `billId`. - - [Bills](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) are invoices that represent the SMB's financial obligations to their supplier for a purchase of goods or services. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.ListBillAttachmentsRequest) - request = cast(operations.ListBillAttachmentsRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/connections/{connectionId}/payables/bills/{billId}/attachments", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="list-bill-attachments", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(List[shared.Attachment], http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "409", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def list_attachments_async( - self, - *, - request: Union[ - operations.ListBillAttachmentsRequest, - operations.ListBillAttachmentsRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> List[shared.Attachment]: - r"""List bill attachments - - The *List bill attachments* endpoint returns a list of attachments available to download for a given `billId`. - - [Bills](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) are invoices that represent the SMB's financial obligations to their supplier for a purchase of goods or services. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.ListBillAttachmentsRequest) - request = cast(operations.ListBillAttachmentsRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/connections/{connectionId}/payables/bills/{billId}/attachments", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="list-bill-attachments", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(List[shared.Attachment], http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "409", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def download_attachment( - self, - *, - request: Union[ - operations.DownloadBillAttachmentRequest, - operations.DownloadBillAttachmentRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> httpx.Response: - r"""Download bill attachment - - The *Download bill attachment* endpoint downloads a specific attachment for a given `billId` and `attachmentId`. - - [Bills](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) are invoices that represent the SMB's financial obligations to their supplier for a purchase of goods or services. - - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.DownloadBillAttachmentRequest) - request = cast(operations.DownloadBillAttachmentRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/connections/{connectionId}/payables/bills/{billId}/attachments/{attachmentId}/download", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/octet-stream", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="download-bill-attachment", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - stream=True, - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/octet-stream"): - return http_res - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - http_res_text = utils.stream_to_text(http_res) - response_data = unmarshal_json_response( - errors.ErrorMessageData, http_res, http_res_text - ) - raise errors.ErrorMessage(response_data, http_res, http_res_text) - if utils.match_response(http_res, ["500", "503"], "application/json"): - http_res_text = utils.stream_to_text(http_res) - response_data = unmarshal_json_response( - errors.ErrorMessageData, http_res, http_res_text - ) - raise errors.ErrorMessage(response_data, http_res, http_res_text) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("Unexpected response received", http_res, http_res_text) - - async def download_attachment_async( - self, - *, - request: Union[ - operations.DownloadBillAttachmentRequest, - operations.DownloadBillAttachmentRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> httpx.Response: - r"""Download bill attachment - - The *Download bill attachment* endpoint downloads a specific attachment for a given `billId` and `attachmentId`. - - [Bills](https://docs.codat.io/sync-for-payables-api#/schemas/Bill) are invoices that represent the SMB's financial obligations to their supplier for a purchase of goods or services. - - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.DownloadBillAttachmentRequest) - request = cast(operations.DownloadBillAttachmentRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/connections/{connectionId}/payables/bills/{billId}/attachments/{attachmentId}/download", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/octet-stream", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="download-bill-attachment", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - stream=True, - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/octet-stream"): - return http_res - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - http_res_text = await utils.stream_to_text_async(http_res) - response_data = unmarshal_json_response( - errors.ErrorMessageData, http_res, http_res_text - ) - raise errors.ErrorMessage(response_data, http_res, http_res_text) - if utils.match_response(http_res, ["500", "503"], "application/json"): - http_res_text = await utils.stream_to_text_async(http_res) - response_data = unmarshal_json_response( - errors.ErrorMessageData, http_res, http_res_text - ) - raise errors.ErrorMessage(response_data, http_res, http_res_text) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("Unexpected response received", http_res, http_res_text) +from codat_sync_for_payables.api.bills import Bills diff --git a/sync-for-payables/src/codat_sync_for_payables/companies.py b/sync-for-payables/src/codat_sync_for_payables/companies.py index a49b9a649..61832db52 100644 --- a/sync-for-payables/src/codat_sync_for_payables/companies.py +++ b/sync-for-payables/src/codat_sync_for_payables/companies.py @@ -1,1285 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.companies — re-export of the companies method group.""" -from .basesdk import BaseSDK -from codat_sync_for_payables import utils -from codat_sync_for_payables._hooks import HookContext -from codat_sync_for_payables.models import errors, operations, shared -from codat_sync_for_payables.types import BaseModel, OptionalNullable, UNSET -from codat_sync_for_payables.utils.unmarshal_json_response import ( - unmarshal_json_response, -) -from typing import Any, Mapping, Optional, Union, cast - - -class Companies(BaseSDK): - r"""Create and manage your SMB users' companies.""" - - def list( - self, - *, - request: Union[ - operations.ListCompaniesRequest, operations.ListCompaniesRequestTypedDict - ] = operations.ListCompaniesRequest(), - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Companies: - r"""List companies - - The *List companies* endpoint returns a list of [companies](https://docs.codat.io/sync-for-payables-api#/schemas/Company) associated to your instances. - - A [company](https://docs.codat.io/sync-for-payables-api#/schemas/Company) represents a business sharing access to their data. - Each company can have multiple [connections](https://docs.codat.io/sync-for-payables-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. - - ## Filter by tags - - The *List companies* endpoint supports the filtering of companies using [tags](https://docs.codat.io/using-the-api/managing-companies#add-metadata-to-a-company). It supports the following operators with [Codat’s query language](https://docs.codat.io/using-the-api/querying): - - - equals (`=`) - - not equals (`!=`) - - contains (`~`) - - For example, you can use the querying to filter companies tagged with a specific foreign key, region, or owning team: - - Foreign key: `uid = {yourCustomerId}` - - Region: `region != uk` - - Owning team and region: `region = uk && owningTeam = invoice-finance` - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.ListCompaniesRequest) - request = cast(operations.ListCompaniesRequest, request) - - req = self._build_request( - method="GET", - path="/companies", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="list-companies", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Companies, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def list_async( - self, - *, - request: Union[ - operations.ListCompaniesRequest, operations.ListCompaniesRequestTypedDict - ] = operations.ListCompaniesRequest(), - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Companies: - r"""List companies - - The *List companies* endpoint returns a list of [companies](https://docs.codat.io/sync-for-payables-api#/schemas/Company) associated to your instances. - - A [company](https://docs.codat.io/sync-for-payables-api#/schemas/Company) represents a business sharing access to their data. - Each company can have multiple [connections](https://docs.codat.io/sync-for-payables-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. - - ## Filter by tags - - The *List companies* endpoint supports the filtering of companies using [tags](https://docs.codat.io/using-the-api/managing-companies#add-metadata-to-a-company). It supports the following operators with [Codat’s query language](https://docs.codat.io/using-the-api/querying): - - - equals (`=`) - - not equals (`!=`) - - contains (`~`) - - For example, you can use the querying to filter companies tagged with a specific foreign key, region, or owning team: - - Foreign key: `uid = {yourCustomerId}` - - Region: `region != uk` - - Owning team and region: `region = uk && owningTeam = invoice-finance` - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.ListCompaniesRequest) - request = cast(operations.ListCompaniesRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="list-companies", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Companies, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def create( - self, - *, - request: Optional[ - Union[shared.CompanyRequestBody, shared.CompanyRequestBodyTypedDict] - ] = None, - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Company: - r"""Create company - - Use the *Create company* endpoint to create a new [company](https://docs.codat.io/sync-for-payables-api#/schemas/Company) that represents your customer in Codat. - - A [company](https://docs.codat.io/sync-for-payables-api#/schemas/Company) represents a business sharing access to their data. - Each company can have multiple [connections](https://docs.codat.io/sync-for-payables-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. - - If forbidden characters (see `name` pattern) are present in the request, a company will be created with the forbidden characters removed. For example, `Company (Codat[1])` with be created as `Company Codat1`. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, Optional[shared.CompanyRequestBody]) - request = cast(Optional[shared.CompanyRequestBody], request) - - req = self._build_request( - method="POST", - path="/companies", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request, False, True, "json", Optional[shared.CompanyRequestBody] - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="create-company", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Company, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def create_async( - self, - *, - request: Optional[ - Union[shared.CompanyRequestBody, shared.CompanyRequestBodyTypedDict] - ] = None, - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Company: - r"""Create company - - Use the *Create company* endpoint to create a new [company](https://docs.codat.io/sync-for-payables-api#/schemas/Company) that represents your customer in Codat. - - A [company](https://docs.codat.io/sync-for-payables-api#/schemas/Company) represents a business sharing access to their data. - Each company can have multiple [connections](https://docs.codat.io/sync-for-payables-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. - - If forbidden characters (see `name` pattern) are present in the request, a company will be created with the forbidden characters removed. For example, `Company (Codat[1])` with be created as `Company Codat1`. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, Optional[shared.CompanyRequestBody]) - request = cast(Optional[shared.CompanyRequestBody], request) - - req = self._build_request_async( - method="POST", - path="/companies", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=False, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request, False, True, "json", Optional[shared.CompanyRequestBody] - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="create-company", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Company, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def replace( - self, - *, - request: Union[ - operations.ReplaceCompanyRequest, operations.ReplaceCompanyRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Company: - r"""Replace company - - Use the *Replace company* endpoint to replace the existing name, description, and tags of the company. Calling the endpoint will replace existing values even if new values haven't been defined in the payload. - - A [company](https://docs.codat.io/sync-for-payables-api#/schemas/Company) represents a business sharing access to their data. - Each company can have multiple [connections](https://docs.codat.io/sync-for-payables-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.ReplaceCompanyRequest) - request = cast(operations.ReplaceCompanyRequest, request) - - req = self._build_request( - method="PUT", - path="/companies/{companyId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.company_request_body if request is not None else None, - False, - True, - "json", - Optional[shared.CompanyRequestBody], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="replace-company", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Company, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def replace_async( - self, - *, - request: Union[ - operations.ReplaceCompanyRequest, operations.ReplaceCompanyRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Company: - r"""Replace company - - Use the *Replace company* endpoint to replace the existing name, description, and tags of the company. Calling the endpoint will replace existing values even if new values haven't been defined in the payload. - - A [company](https://docs.codat.io/sync-for-payables-api#/schemas/Company) represents a business sharing access to their data. - Each company can have multiple [connections](https://docs.codat.io/sync-for-payables-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.ReplaceCompanyRequest) - request = cast(operations.ReplaceCompanyRequest, request) - - req = self._build_request_async( - method="PUT", - path="/companies/{companyId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.company_request_body if request is not None else None, - False, - True, - "json", - Optional[shared.CompanyRequestBody], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="replace-company", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Company, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def update( - self, - *, - request: Union[ - operations.UpdateCompanyRequest, operations.UpdateCompanyRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Company: - r"""Update company - - Use the *Update company* endpoint to update the name, description, or tags of the company. - - The *Update company* endpoint doesn't have any required fields. If any of the fields provided are `null` or not provided, they won't be included in the update. - - A [company](https://docs.codat.io/sync-for-payables-api#/schemas/Company) represents a business sharing access to their data. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.UpdateCompanyRequest) - request = cast(operations.UpdateCompanyRequest, request) - - req = self._build_request( - method="PATCH", - path="/companies/{companyId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.company_update_request if request is not None else None, - False, - True, - "json", - Optional[shared.CompanyUpdateRequest], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="update-company", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Company, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def update_async( - self, - *, - request: Union[ - operations.UpdateCompanyRequest, operations.UpdateCompanyRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Company: - r"""Update company - - Use the *Update company* endpoint to update the name, description, or tags of the company. - - The *Update company* endpoint doesn't have any required fields. If any of the fields provided are `null` or not provided, they won't be included in the update. - - A [company](https://docs.codat.io/sync-for-payables-api#/schemas/Company) represents a business sharing access to their data. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.UpdateCompanyRequest) - request = cast(operations.UpdateCompanyRequest, request) - - req = self._build_request_async( - method="PATCH", - path="/companies/{companyId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.company_update_request if request is not None else None, - False, - True, - "json", - Optional[shared.CompanyUpdateRequest], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="update-company", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Company, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def delete( - self, - *, - request: Union[ - operations.DeleteCompanyRequest, operations.DeleteCompanyRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ): - r"""Delete a company - - The *Delete company* endpoint permanently deletes a [company](https://docs.codat.io/sync-for-payables-api#/schemas/Company), its [connections](https://docs.codat.io/sync-for-payables-api#/schemas/Connection) and any cached data. This operation is irreversible. - - A [company](https://docs.codat.io/sync-for-payables-api#/schemas/Company) represents a business sharing access to their data. - Each company can have multiple [connections](https://docs.codat.io/sync-for-payables-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. - - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.DeleteCompanyRequest) - request = cast(operations.DeleteCompanyRequest, request) - - req = self._build_request( - method="DELETE", - path="/companies/{companyId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="delete-company", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "204", "*"): - return - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def delete_async( - self, - *, - request: Union[ - operations.DeleteCompanyRequest, operations.DeleteCompanyRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ): - r"""Delete a company - - The *Delete company* endpoint permanently deletes a [company](https://docs.codat.io/sync-for-payables-api#/schemas/Company), its [connections](https://docs.codat.io/sync-for-payables-api#/schemas/Connection) and any cached data. This operation is irreversible. - - A [company](https://docs.codat.io/sync-for-payables-api#/schemas/Company) represents a business sharing access to their data. - Each company can have multiple [connections](https://docs.codat.io/sync-for-payables-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. - - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.DeleteCompanyRequest) - request = cast(operations.DeleteCompanyRequest, request) - - req = self._build_request_async( - method="DELETE", - path="/companies/{companyId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="delete-company", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "204", "*"): - return - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def get( - self, - *, - request: Union[ - operations.GetCompanyRequest, operations.GetCompanyRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Company: - r"""Get company - - The *Get company* endpoint returns a single company for a given `companyId`. - - A [company](https://docs.codat.io/sync-for-payables-api#/schemas/Company) represents a business sharing access to their data. - Each company can have multiple [connections](https://docs.codat.io/sync-for-payables-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. - - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.GetCompanyRequest) - request = cast(operations.GetCompanyRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-company", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Company, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def get_async( - self, - *, - request: Union[ - operations.GetCompanyRequest, operations.GetCompanyRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Company: - r"""Get company - - The *Get company* endpoint returns a single company for a given `companyId`. - - A [company](https://docs.codat.io/sync-for-payables-api#/schemas/Company) represents a business sharing access to their data. - Each company can have multiple [connections](https://docs.codat.io/sync-for-payables-api#/schemas/Connection) to different data sources, such as one connection to Xero for accounting data, two connections to Plaid for two bank accounts, and a connection to Zettle for POS data. - - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.GetCompanyRequest) - request = cast(operations.GetCompanyRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-company", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Company, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) +from codat_sync_for_payables.api.companies import Companies diff --git a/sync-for-payables/src/codat_sync_for_payables/company_information.py b/sync-for-payables/src/codat_sync_for_payables/company_information.py index 939ae1b15..cbac86972 100644 --- a/sync-for-payables/src/codat_sync_for_payables/company_information.py +++ b/sync-for-payables/src/codat_sync_for_payables/company_information.py @@ -1,215 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.company_information — re-export of the company_information method group.""" -from .basesdk import BaseSDK -from codat_sync_for_payables import utils -from codat_sync_for_payables._hooks import HookContext -from codat_sync_for_payables.models import errors, operations, shared -from codat_sync_for_payables.types import BaseModel, OptionalNullable, UNSET -from codat_sync_for_payables.utils.unmarshal_json_response import ( - unmarshal_json_response, -) -from typing import Any, Mapping, Optional, Union, cast - - -class CompanyInformation(BaseSDK): - r"""View company profile from the source platform.""" - - def get( - self, - *, - request: Union[ - operations.GetCompanyInformationRequest, - operations.GetCompanyInformationRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.CompanyInformation: - r"""Get company information - - Use the *Get company information* endpoint to return information about the company available from the underlying accounting software. - - - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.GetCompanyInformationRequest) - request = cast(operations.GetCompanyInformationRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/connections/{connectionId}/payables/info", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-company-information", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.CompanyInformation, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def get_async( - self, - *, - request: Union[ - operations.GetCompanyInformationRequest, - operations.GetCompanyInformationRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.CompanyInformation: - r"""Get company information - - Use the *Get company information* endpoint to return information about the company available from the underlying accounting software. - - - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.GetCompanyInformationRequest) - request = cast(operations.GetCompanyInformationRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/connections/{connectionId}/payables/info", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-company-information", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.CompanyInformation, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) +from codat_sync_for_payables.api.company_information import CompanyInformation diff --git a/sync-for-payables/src/codat_sync_for_payables/configuration.py b/sync-for-payables/src/codat_sync_for_payables/configuration.py new file mode 100644 index 000000000..fe34b2ddc --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/configuration.py @@ -0,0 +1,596 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import copy +import http.client as httplib +import logging +from logging import FileHandler +import multiprocessing +import sys +from typing import Any, ClassVar, Dict, List, Literal, Optional, TypedDict +from typing_extensions import NotRequired, Self + +import urllib3 + + +JSON_SCHEMA_VALIDATION_KEYWORDS = { + 'multipleOf', 'maximum', 'exclusiveMaximum', + 'minimum', 'exclusiveMinimum', 'maxLength', + 'minLength', 'pattern', 'maxItems', 'minItems' +} + +ServerVariablesT = Dict[str, str] + +GenericAuthSetting = TypedDict( + "GenericAuthSetting", + { + "type": str, + "in": str, + "key": str, + "value": str, + }, +) + + +OAuth2AuthSetting = TypedDict( + "OAuth2AuthSetting", + { + "type": Literal["oauth2"], + "in": Literal["header"], + "key": Literal["Authorization"], + "value": str, + }, +) + + +APIKeyAuthSetting = TypedDict( + "APIKeyAuthSetting", + { + "type": Literal["api_key"], + "in": str, + "key": str, + "value": Optional[str], + }, +) + + +BasicAuthSetting = TypedDict( + "BasicAuthSetting", + { + "type": Literal["basic"], + "in": Literal["header"], + "key": Literal["Authorization"], + "value": Optional[str], + }, +) + + +BearerFormatAuthSetting = TypedDict( + "BearerFormatAuthSetting", + { + "type": Literal["bearer"], + "in": Literal["header"], + "format": Literal["JWT"], + "key": Literal["Authorization"], + "value": str, + }, +) + + +BearerAuthSetting = TypedDict( + "BearerAuthSetting", + { + "type": Literal["bearer"], + "in": Literal["header"], + "key": Literal["Authorization"], + "value": str, + }, +) + + +HTTPSignatureAuthSetting = TypedDict( + "HTTPSignatureAuthSetting", + { + "type": Literal["http-signature"], + "in": Literal["header"], + "key": Literal["Authorization"], + "value": None, + }, +) + + +AuthSettings = TypedDict( + "AuthSettings", + { + "auth_header": APIKeyAuthSetting, + }, + total=False, +) + + +class HostSettingVariable(TypedDict): + description: str + default_value: str + enum_values: List[str] + + +class HostSetting(TypedDict): + url: str + description: str + variables: NotRequired[Dict[str, HostSettingVariable]] + + +class Configuration: + """This class contains various settings of the API client. + + :param host: Base url. + :param ignore_operation_servers + Boolean to ignore operation servers for the API client. + Config will use `host` as the base url regardless of the operation servers. + :param api_key: Dict to store API key(s). + Each entry in the dict specifies an API key. + The dict key is the name of the security scheme in the OAS specification. + The dict value is the API key secret. + :param api_key_prefix: Dict to store API prefix (e.g. Bearer). + The dict key is the name of the security scheme in the OAS specification. + The dict value is an API key prefix when generating the auth data. + :param username: Username for HTTP basic authentication. + :param password: Password for HTTP basic authentication. + :param access_token: Access token. + :param server_index: Index to servers configuration. + :param server_variables: Mapping with string values to replace variables in + templated server configuration. The validation of enums is performed for + variables with defined enum values before. + :param server_operation_index: Mapping from operation ID to an index to server + configuration. + :param server_operation_variables: Mapping from operation ID to a mapping with + string values to replace variables in templated server configuration. + The validation of enums is performed for variables with defined enum + values before. + :param ssl_ca_cert: str - the path to a file of concatenated CA certificates + in PEM format. + :param retries: Number of retries for API requests. + + :Example: + + API Key Authentication Example. + Given the following security scheme in the OpenAPI specification: + components: + securitySchemes: + cookieAuth: # name for the security scheme + type: apiKey + in: cookie + name: JSESSIONID # cookie name + + You can programmatically set the cookie: + +conf = codat_sync_for_payables.Configuration( + api_key={'cookieAuth': 'abc123'} + api_key_prefix={'cookieAuth': 'JSESSIONID'} +) + + The following cookie will be added to the HTTP request: + Cookie: JSESSIONID abc123 + """ + + _default: ClassVar[Optional[Self]] = None + + def __init__( + self, + host: Optional[str]=None, + api_key: Optional[Dict[str, str]]=None, + api_key_prefix: Optional[Dict[str, str]]=None, + username: Optional[str]=None, + password: Optional[str]=None, + access_token: Optional[str]=None, + server_index: Optional[int]=None, + server_variables: Optional[ServerVariablesT]=None, + server_operation_index: Optional[Dict[int, int]]=None, + server_operation_variables: Optional[Dict[int, ServerVariablesT]]=None, + ignore_operation_servers: bool=False, + ssl_ca_cert: Optional[str]=None, + retries: Optional[int] = None, + *, + debug: Optional[bool] = None, + ) -> None: + """Constructor + """ + self._base_path = "https://api.codat.io" if host is None else host + """Default Base url + """ + self.server_index = 0 if server_index is None and host is None else server_index + self.server_operation_index = server_operation_index or {} + """Default server index + """ + self.server_variables = server_variables or {} + self.server_operation_variables = server_operation_variables or {} + """Default server variables + """ + self.ignore_operation_servers = ignore_operation_servers + """Ignore operation servers + """ + self.temp_folder_path = None + """Temp file folder for downloading files + """ + # Authentication Settings + self.api_key = {} + if api_key: + self.api_key = api_key + """dict to store API key(s) + """ + self.api_key_prefix = {} + if api_key_prefix: + self.api_key_prefix = api_key_prefix + """dict to store API prefix (e.g. Bearer) + """ + self.refresh_api_key_hook = None + """function hook to refresh API key if expired + """ + self.username = username + """Username for HTTP basic authentication + """ + self.password = password + """Password for HTTP basic authentication + """ + self.access_token = access_token + """Access token + """ + self.logger = {} + """Logging Settings + """ + self.logger["package_logger"] = logging.getLogger("codat_sync_for_payables") + self.logger["urllib3_logger"] = logging.getLogger("urllib3") + self.logger_format = '%(asctime)s %(levelname)s %(message)s' + """Log format + """ + self.logger_stream_handler = None + """Log stream handler + """ + self.logger_file_handler: Optional[FileHandler] = None + """Log file handler + """ + self.logger_file = None + """Debug file location + """ + if debug is not None: + self.debug = debug + else: + self.__debug = False + """Debug switch + """ + + self.verify_ssl = True + """SSL/TLS verification + Set this to false to skip verifying SSL certificate when calling API + from https server. + """ + self.ssl_ca_cert = ssl_ca_cert + """Set this to customize the certificate file to verify the peer. + """ + self.cert_file = None + """client certificate file + """ + self.key_file = None + """client key file + """ + self.assert_hostname = None + """Set this to True/False to enable/disable SSL hostname verification. + """ + self.tls_server_name = None + """SSL/TLS Server Name Indication (SNI) + Set this to the SNI value expected by the server. + """ + + self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 + """urllib3 connection pool's maximum number of connections saved + per pool. urllib3 uses 1 connection as default value, but this is + not the best value when you are making a lot of possibly parallel + requests to the same host, which is often the case here. + cpu_count * 5 is used as default value to increase performance. + """ + + self.proxy: Optional[str] = None + """Proxy URL + """ + self.proxy_headers = None + """Proxy headers + """ + self.safe_chars_for_path_param = '' + """Safe chars for path_param + """ + self.retries = retries + """Adding retries to override urllib3 default value 3 + """ + # Enable client side validation + self.client_side_validation = True + + self.socket_options = None + """Options to pass down to the underlying urllib3 socket + """ + + self.datetime_format = "%Y-%m-%dT%H:%M:%S.%f%z" + """datetime format + """ + + self.date_format = "%Y-%m-%d" + """date format + """ + + def __deepcopy__(self, memo: Dict[int, Any]) -> Self: + cls = self.__class__ + result = cls.__new__(cls) + memo[id(self)] = result + for k, v in self.__dict__.items(): + if k not in ('logger', 'logger_file_handler'): + setattr(result, k, copy.deepcopy(v, memo)) + # shallow copy of loggers + result.logger = copy.copy(self.logger) + # use setters to configure loggers + result.logger_file = self.logger_file + result.debug = self.debug + return result + + def __setattr__(self, name: str, value: Any) -> None: + object.__setattr__(self, name, value) + + @classmethod + def set_default(cls, default: Optional[Self]) -> None: + """Set default instance of configuration. + + It stores default configuration, which can be + returned by get_default_copy method. + + :param default: object of Configuration + """ + cls._default = default + + @classmethod + def get_default_copy(cls) -> Self: + """Deprecated. Please use `get_default` instead. + + Deprecated. Please use `get_default` instead. + + :return: The configuration object. + """ + return cls.get_default() + + @classmethod + def get_default(cls) -> Self: + """Return the default configuration. + + This method returns newly created, based on default constructor, + object of Configuration class or returns a copy of default + configuration. + + :return: The configuration object. + """ + if cls._default is None: + cls._default = cls() + return cls._default + + @property + def logger_file(self) -> Optional[str]: + """The logger file. + + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str + """ + return self.__logger_file + + @logger_file.setter + def logger_file(self, value: Optional[str]) -> None: + """The logger file. + + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str + """ + self.__logger_file = value + if self.__logger_file: + # If set logging file, + # then add file handler and remove stream handler. + self.logger_file_handler = logging.FileHandler(self.__logger_file) + self.logger_file_handler.setFormatter(self.logger_formatter) + for _, logger in self.logger.items(): + logger.addHandler(self.logger_file_handler) + + @property + def debug(self) -> bool: + """Debug status + + :param value: The debug status, True or False. + :type: bool + """ + return self.__debug + + @debug.setter + def debug(self, value: bool) -> None: + """Debug status + + :param value: The debug status, True or False. + :type: bool + """ + self.__debug = value + if self.__debug: + # if debug status is True, turn on debug logging + for _, logger in self.logger.items(): + logger.setLevel(logging.DEBUG) + # turn on httplib debug + httplib.HTTPConnection.debuglevel = 1 + else: + # if debug status is False, turn off debug logging, + # setting log level to default `logging.WARNING` + for _, logger in self.logger.items(): + logger.setLevel(logging.WARNING) + # turn off httplib debug + httplib.HTTPConnection.debuglevel = 0 + + @property + def logger_format(self) -> str: + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str + """ + return self.__logger_format + + @logger_format.setter + def logger_format(self, value: str) -> None: + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str + """ + self.__logger_format = value + self.logger_formatter = logging.Formatter(self.__logger_format) + + def get_api_key_with_prefix(self, identifier: str, alias: Optional[str]=None) -> Optional[str]: + """Gets API key (with prefix if set). + + :param identifier: The identifier of apiKey. + :param alias: The alternative identifier of apiKey. + :return: The token for api key authentication. + """ + if self.refresh_api_key_hook is not None: + self.refresh_api_key_hook(self) + key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None) + if key: + prefix = self.api_key_prefix.get(identifier) + if prefix: + return "%s %s" % (prefix, key) + else: + return key + + return None + + def get_basic_auth_token(self) -> Optional[str]: + """Gets HTTP basic authentication header (string). + + :return: The token for basic HTTP authentication. + """ + username = "" + if self.username is not None: + username = self.username + password = "" + if self.password is not None: + password = self.password + return urllib3.util.make_headers( + basic_auth=username + ':' + password + ).get('authorization') + + def auth_settings(self)-> AuthSettings: + """Gets Auth Settings dict for api client. + + :return: The Auth Settings information dict. + """ + auth: AuthSettings = {} + if 'auth_header' in self.api_key: + auth['auth_header'] = { + 'type': 'api_key', + 'in': 'header', + 'key': 'Authorization', + 'value': self.get_api_key_with_prefix( + 'auth_header', + ), + } + return auth + + def to_debug_report(self) -> str: + """Gets the essential information for debugging. + + :return: The report for debugging. + """ + return "Python SDK Debug Report:\n"\ + "OS: {env}\n"\ + "Python Version: {pyversion}\n"\ + "Version of the API: 3.0.0\n"\ + "SDK Package Version: 1.0.0".\ + format(env=sys.platform, pyversion=sys.version) + + def get_host_settings(self) -> List[HostSetting]: + """Gets an array of host settings + + :return: An array of host settings + """ + return [ + { + 'url': "https://api.codat.io", + 'description': "Production", + } + ] + + def get_host_from_settings( + self, + index: Optional[int], + variables: Optional[ServerVariablesT]=None, + servers: Optional[List[HostSetting]]=None, + ) -> str: + """Gets host URL based on the index and variables + :param index: array index of the host settings + :param variables: hash of variable and the corresponding value + :param servers: an array of host settings or None + :return: URL based on host settings + """ + if index is None: + return self._base_path + + variables = {} if variables is None else variables + servers = self.get_host_settings() if servers is None else servers + + try: + server = servers[index] + except IndexError: + raise ValueError( + "Invalid index {0} when selecting the host settings. " + "Must be less than {1}".format(index, len(servers))) + + url = server['url'] + + # go through variables and replace placeholders + for variable_name, variable in server.get('variables', {}).items(): + used_value = variables.get( + variable_name, variable['default_value']) + + if 'enum_values' in variable \ + and used_value not in variable['enum_values']: + raise ValueError( + "The variable `{0}` in the host URL has invalid value " + "{1}. Must be {2}.".format( + variable_name, variables[variable_name], + variable['enum_values'])) + + url = url.replace("{" + variable_name + "}", used_value) + + return url + + @property + def host(self) -> str: + """Return generated host.""" + return self.get_host_from_settings(self.server_index, variables=self.server_variables) + + @host.setter + def host(self, value: str) -> None: + """Fix base path.""" + self._base_path = value + self.server_index = None diff --git a/sync-for-payables/src/codat_sync_for_payables/connections.py b/sync-for-payables/src/codat_sync_for_payables/connections.py index 2bb868a4a..c22c4f736 100644 --- a/sync-for-payables/src/codat_sync_for_payables/connections.py +++ b/sync-for-payables/src/codat_sync_for_payables/connections.py @@ -1,1027 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.connections — re-export of the connections method group.""" -from .basesdk import BaseSDK -from codat_sync_for_payables import utils -from codat_sync_for_payables._hooks import HookContext -from codat_sync_for_payables.models import errors, operations, shared -from codat_sync_for_payables.types import BaseModel, OptionalNullable, UNSET -from codat_sync_for_payables.utils.unmarshal_json_response import ( - unmarshal_json_response, -) -from typing import Any, Mapping, Optional, Union, cast - - -class Connections(BaseSDK): - r"""Create new and manage existing data connections for a company.""" - - def list( - self, - *, - request: Union[ - operations.ListConnectionsRequest, - operations.ListConnectionsRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Connections: - r"""List connections - - List the connections for a company. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.ListConnectionsRequest) - request = cast(operations.ListConnectionsRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/connections", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="list-connections", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Connections, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def list_async( - self, - *, - request: Union[ - operations.ListConnectionsRequest, - operations.ListConnectionsRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Connections: - r"""List connections - - List the connections for a company. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.ListConnectionsRequest) - request = cast(operations.ListConnectionsRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/connections", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="list-connections", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Connections, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def create( - self, - *, - request: Union[ - operations.CreateConnectionRequest, - operations.CreateConnectionRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Connection: - r"""Create connection - - Creates a connection for the company by providing a valid `platformKey`. - - Use the [List Integrations](https://docs.codat.io/platform-api#/operations/list-integrations) endpoint to access valid platform keys. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.CreateConnectionRequest) - request = cast(operations.CreateConnectionRequest, request) - - req = self._build_request( - method="POST", - path="/companies/{companyId}/connections", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.request_body if request is not None else None, - False, - True, - "json", - Optional[operations.CreateConnectionRequestBody], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="create-connection", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Connection, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def create_async( - self, - *, - request: Union[ - operations.CreateConnectionRequest, - operations.CreateConnectionRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Connection: - r"""Create connection - - Creates a connection for the company by providing a valid `platformKey`. - - Use the [List Integrations](https://docs.codat.io/platform-api#/operations/list-integrations) endpoint to access valid platform keys. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.CreateConnectionRequest) - request = cast(operations.CreateConnectionRequest, request) - - req = self._build_request_async( - method="POST", - path="/companies/{companyId}/connections", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.request_body if request is not None else None, - False, - True, - "json", - Optional[operations.CreateConnectionRequestBody], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="create-connection", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Connection, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def get( - self, - *, - request: Union[ - operations.GetConnectionRequest, operations.GetConnectionRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Connection: - r"""Get connection - - Returns a specific connection for a company when valid identifiers are provided. If the identifiers are for a deleted company and/or connection, a not found response is returned. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.GetConnectionRequest) - request = cast(operations.GetConnectionRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/connections/{connectionId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-connection", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Connection, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def get_async( - self, - *, - request: Union[ - operations.GetConnectionRequest, operations.GetConnectionRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Connection: - r"""Get connection - - Returns a specific connection for a company when valid identifiers are provided. If the identifiers are for a deleted company and/or connection, a not found response is returned. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.GetConnectionRequest) - request = cast(operations.GetConnectionRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/connections/{connectionId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="get-connection", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Connection, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def delete( - self, - *, - request: Union[ - operations.DeleteConnectionRequest, - operations.DeleteConnectionRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ): - r"""Delete connection - - Revoke and remove a connection from a company. - This operation is not reversible. The end user would need to reauthorize a new data connection if you wish to view new data for this company. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.DeleteConnectionRequest) - request = cast(operations.DeleteConnectionRequest, request) - - req = self._build_request( - method="DELETE", - path="/companies/{companyId}/connections/{connectionId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="delete-connection", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "*"): - return - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def delete_async( - self, - *, - request: Union[ - operations.DeleteConnectionRequest, - operations.DeleteConnectionRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ): - r"""Delete connection - - Revoke and remove a connection from a company. - This operation is not reversible. The end user would need to reauthorize a new data connection if you wish to view new data for this company. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.DeleteConnectionRequest) - request = cast(operations.DeleteConnectionRequest, request) - - req = self._build_request_async( - method="DELETE", - path="/companies/{companyId}/connections/{connectionId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="delete-connection", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "*"): - return - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def unlink( - self, - *, - request: Union[ - operations.UnlinkConnectionRequest, - operations.UnlinkConnectionRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Connection: - r"""Unlink connection - - This allows you to deauthorize a connection, without deleting it from Codat. This means you can still view any data that has previously been pulled into Codat, and also lets you re-authorize in future if your customer wishes to resume sharing their data. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.UnlinkConnectionRequest) - request = cast(operations.UnlinkConnectionRequest, request) - - req = self._build_request( - method="PATCH", - path="/companies/{companyId}/connections/{connectionId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.request_body if request is not None else None, - False, - True, - "json", - Optional[operations.UnlinkConnectionUpdateConnection], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="unlink-connection", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Connection, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def unlink_async( - self, - *, - request: Union[ - operations.UnlinkConnectionRequest, - operations.UnlinkConnectionRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Connection: - r"""Unlink connection - - This allows you to deauthorize a connection, without deleting it from Codat. This means you can still view any data that has previously been pulled into Codat, and also lets you re-authorize in future if your customer wishes to resume sharing their data. - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.UnlinkConnectionRequest) - request = cast(operations.UnlinkConnectionRequest, request) - - req = self._build_request_async( - method="PATCH", - path="/companies/{companyId}/connections/{connectionId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.request_body if request is not None else None, - False, - True, - "json", - Optional[operations.UnlinkConnectionUpdateConnection], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="unlink-connection", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Connection, http_res) - if utils.match_response( - http_res, ["401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) +from codat_sync_for_payables.api.connections import Connections diff --git a/sync-for-payables/src/codat_sync_for_payables/exceptions.py b/sync-for-payables/src/codat_sync_for_payables/exceptions.py new file mode 100644 index 000000000..cf45b5fe7 --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/exceptions.py @@ -0,0 +1,200 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from typing import Any, Optional +from typing_extensions import Self + +class OpenApiException(Exception): + """The base exception class for all OpenAPIExceptions""" + + +class ApiTypeError(OpenApiException, TypeError): + def __init__(self, msg, path_to_item=None, valid_classes=None, + key_type=None) -> None: + """ Raises an exception for TypeErrors + + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (list): a list of keys an indices to get to the + current_item + None if unset + valid_classes (tuple): the primitive classes that current item + should be an instance of + None if unset + key_type (bool): False if our value is a value in a dict + True if it is a key in a dict + False if our item is an item in a list + None if unset + """ + self.path_to_item = path_to_item + self.valid_classes = valid_classes + self.key_type = key_type + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiTypeError, self).__init__(full_msg) + + +class ApiValueError(OpenApiException, ValueError): + def __init__(self, msg, path_to_item=None) -> None: + """ + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (list) the path to the exception in the + received_data dict. None if unset + """ + + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiValueError, self).__init__(full_msg) + + +class ApiAttributeError(OpenApiException, AttributeError): + def __init__(self, msg, path_to_item=None) -> None: + """ + Raised when an attribute reference or assignment fails. + + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (None/list) the path to the exception in the + received_data dict + """ + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiAttributeError, self).__init__(full_msg) + + +class ApiKeyError(OpenApiException, KeyError): + def __init__(self, msg, path_to_item=None) -> None: + """ + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (None/list) the path to the exception in the + received_data dict + """ + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiKeyError, self).__init__(full_msg) + + +class ApiException(OpenApiException): + + def __init__( + self, + status=None, + reason=None, + http_resp=None, + *, + body: Optional[str] = None, + data: Optional[Any] = None, + ) -> None: + self.status = status + self.reason = reason + self.body = body + self.data = data + self.headers = None + + if http_resp: + if self.status is None: + self.status = http_resp.status + if self.reason is None: + self.reason = http_resp.reason + if self.body is None: + try: + self.body = http_resp.data.decode('utf-8') + except Exception: + pass + self.headers = http_resp.getheaders() + + @classmethod + def from_response( + cls, + *, + http_resp, + body: Optional[str], + data: Optional[Any], + ) -> Self: + if http_resp.status == 400: + raise BadRequestException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 401: + raise UnauthorizedException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 403: + raise ForbiddenException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 404: + raise NotFoundException(http_resp=http_resp, body=body, data=data) + + if 500 <= http_resp.status <= 599: + raise ServiceException(http_resp=http_resp, body=body, data=data) + raise ApiException(http_resp=http_resp, body=body, data=data) + + def __str__(self): + """Custom error messages for exception""" + error_message = "({0})\n"\ + "Reason: {1}\n".format(self.status, self.reason) + if self.headers: + error_message += "HTTP response headers: {0}\n".format( + self.headers) + + if self.data or self.body: + error_message += "HTTP response body: {0}\n".format(self.data or self.body) + + return error_message + + +class BadRequestException(ApiException): + pass + + +class NotFoundException(ApiException): + pass + + +class UnauthorizedException(ApiException): + pass + + +class ForbiddenException(ApiException): + pass + + +class ServiceException(ApiException): + pass + + +def render_path(path_to_item): + """Returns a string representation of a path""" + result = "" + for pth in path_to_item: + if isinstance(pth, int): + result += "[{0}]".format(pth) + else: + result += "['{0}']".format(pth) + return result diff --git a/sync-for-payables/src/codat_sync_for_payables/models/__init__.py b/sync-for-payables/src/codat_sync_for_payables/models/__init__.py index 60ff1284e..d1709aaa9 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/__init__.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/__init__.py @@ -1,23 +1,85 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from typing import Any, TYPE_CHECKING +# flake8: noqa +""" + Bill pay (synchronous solution) -from codat_sync_for_payables.utils.dynamic_imports import lazy_getattr, lazy_dir + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | -if TYPE_CHECKING: - from . import errors, operations, shared + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) -# package + Do not edit the class manually. +""" # noqa: E501 -_sub_packages = ["errors", "operations", "shared"] - - -def __getattr__(attr_name: str) -> Any: - return lazy_getattr( - attr_name, package=__package__, dynamic_imports={}, sub_packages=_sub_packages - ) - - -def __dir__(): - return lazy_dir(dynamic_imports={}, sub_packages=_sub_packages) +# import models into model package +from codat_sync_for_payables.models.shared.accountmappingoption import AccountMappingOption +from codat_sync_for_payables.models.shared.accountstatus import AccountStatus +from codat_sync_for_payables.models.shared.address import Address +from codat_sync_for_payables.models.shared.addresstype import AddressType +from codat_sync_for_payables.models.shared.attachment import Attachment +from codat_sync_for_payables.models.shared.bankaccount import BankAccount +from codat_sync_for_payables.models.shared.bankaccountmappingoption import BankAccountMappingOption +from codat_sync_for_payables.models.shared.bankaccountprototype import BankAccountPrototype +from codat_sync_for_payables.models.shared.bankaccountstatus import BankAccountStatus +from codat_sync_for_payables.models.shared.bankaccounttype import BankAccountType +from codat_sync_for_payables.models.shared.bill import Bill +from codat_sync_for_payables.models.shared.billaccountref import BillAccountRef +from codat_sync_for_payables.models.bill_event_payload import BillEventPayload +from codat_sync_for_payables.models.bill_event_webhook import BillEventWebhook +from codat_sync_for_payables.models.shared.billlineitem import BillLineItem +from codat_sync_for_payables.models.shared.billmappingoptions import BillMappingOptions +from codat_sync_for_payables.models.shared.billpayment import BillPayment +from codat_sync_for_payables.models.shared.billpaymentaccountref import BillPaymentAccountRef +from codat_sync_for_payables.models.shared.billpaymentprototype import BillPaymentPrototype +from codat_sync_for_payables.models.shared.billprototype import BillPrototype +from codat_sync_for_payables.models.shared.billstatus import BillStatus +from codat_sync_for_payables.models.shared.billtaxrateref import BillTaxRateRef +from codat_sync_for_payables.models.shared.bills import Bills +from codat_sync_for_payables.models.shared.clientratelimitwebhook import ClientRateLimitWebhook +from codat_sync_for_payables.models.shared.clientratelimitwebhookpayload import ClientRateLimitWebhookPayload +from codat_sync_for_payables.models.shared.companies import Companies +from codat_sync_for_payables.models.shared.company import Company +from codat_sync_for_payables.models.company_details import CompanyDetails +from codat_sync_for_payables.models.shared.companyinformation import CompanyInformation +from codat_sync_for_payables.models.shared.companyreference import CompanyReference +from codat_sync_for_payables.models.company_reference_links import CompanyReferenceLinks +from codat_sync_for_payables.models.shared.companyrequestbody import CompanyRequestBody +from codat_sync_for_payables.models.shared.companyupdaterequest import CompanyUpdateRequest +from codat_sync_for_payables.models.shared.connection import Connection +from codat_sync_for_payables.models.shared.connections import Connections +from codat_sync_for_payables.models.create_connection_request import CreateConnectionRequest +from codat_sync_for_payables.models.shared.dataconnectionerror import DataConnectionError +from codat_sync_for_payables.models.shared.dataconnectionstatus import DataConnectionStatus +from codat_sync_for_payables.models.data_status import DataStatus +from codat_sync_for_payables.models.data_type import DataType +from codat_sync_for_payables.models.error_message import ErrorMessage +from codat_sync_for_payables.models.shared.errorvalidation import ErrorValidation +from codat_sync_for_payables.models.shared.errorvalidationitem import ErrorValidationItem +from codat_sync_for_payables.models.shared.halref import HalRef +from codat_sync_for_payables.models.shared.links import Links +from codat_sync_for_payables.models.shared.pagination import Pagination +from codat_sync_for_payables.models.paging_info import PagingInfo +from codat_sync_for_payables.models.shared.paymentmappingoptions import PaymentMappingOptions +from codat_sync_for_payables.models.pull_operation import PullOperation +from codat_sync_for_payables.models.pull_operations import PullOperations +from codat_sync_for_payables.models.push_change_type import PushChangeType +from codat_sync_for_payables.models.push_operation import PushOperation +from codat_sync_for_payables.models.push_operation_change import PushOperationChange +from codat_sync_for_payables.models.push_operation_ref import PushOperationRef +from codat_sync_for_payables.models.push_operation_status import PushOperationStatus +from codat_sync_for_payables.models.push_operations import PushOperations +from codat_sync_for_payables.models.source_modified_date import SourceModifiedDate +from codat_sync_for_payables.models.status import Status +from codat_sync_for_payables.models.shared.supplier import Supplier +from codat_sync_for_payables.models.shared.supplierprototype import SupplierPrototype +from codat_sync_for_payables.models.shared.supplierref import SupplierRef +from codat_sync_for_payables.models.shared.supplierstatus import SupplierStatus +from codat_sync_for_payables.models.shared.suppliers import Suppliers +from codat_sync_for_payables.models.shared.taxratemappingoption import TaxRateMappingOption +from codat_sync_for_payables.models.shared.trackingref import TrackingRef +from codat_sync_for_payables.models.update_connection import UpdateConnection +from codat_sync_for_payables.models.validation import Validation +from codat_sync_for_payables.models.validation_item import ValidationItem diff --git a/sync-for-payables/src/codat_sync_for_payables/models/bill_data_type.py b/sync-for-payables/src/codat_sync_for_payables/models/bill_data_type.py new file mode 100644 index 000000000..69407c211 --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/models/bill_data_type.py @@ -0,0 +1,9 @@ +from __future__ import annotations + +from enum import Enum + + +class BillDataType(str, Enum): + """BillDataType enum (lifted from inline OAS enum).""" + TRACKING_CATEGORIES = 'trackingCategories' + CUSTOMERS = 'customers' diff --git a/sync-for-payables/src/codat_sync_for_payables/models/bill_event_payload.py b/sync-for-payables/src/codat_sync_for_payables/models/bill_event_payload.py new file mode 100644 index 000000000..603b40609 --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/models/bill_event_payload.py @@ -0,0 +1,112 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_sync_for_payables.models.shared.bill import Bill, BillTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class BillEventPayload(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + BillEventPayload + """ # noqa: E501 + company_id: Optional[str] = Field(default=None, description="Unique identifier for your SMB in Codat.", alias="companyId") + connection_id: Optional[str] = Field(default=None, description="Unique identifier for a company's data connection.", alias="connectionId") + push_operation_key: Optional[str] = Field(default=None, description="Unique identifier for the push operation.", alias="pushOperationKey") + bill: Optional[Bill] = None + __properties: ClassVar[List[str]] = ["companyId", "connectionId", "pushOperationKey", "bill"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of BillEventPayload from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of bill + if self.bill: + _dict['bill'] = self.bill.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of BillEventPayload from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "companyId": obj.get("companyId"), + "connectionId": obj.get("connectionId"), + "pushOperationKey": obj.get("pushOperationKey"), + "bill": Bill.from_dict(obj["bill"]) if obj.get("bill") is not None else None + }) + return _obj + + + + + +class BillEventPayloadTypedDict(TypedDict): + """TypedDict variant of BillEventPayload, for dict-literal request/response inputs.""" + company_id: NotRequired[Optional[str]] + connection_id: NotRequired[Optional[str]] + push_operation_key: NotRequired[Optional[str]] + bill: NotRequired[Optional[BillTypedDict]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/bill_event_webhook.py b/sync-for-payables/src/codat_sync_for_payables/models/bill_event_webhook.py new file mode 100644 index 000000000..3efd046f2 --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/models/bill_event_webhook.py @@ -0,0 +1,112 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_sync_for_payables.models.bill_event_payload import BillEventPayload, BillEventPayloadTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class BillEventWebhook(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + BillEventWebhook + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Unique identifier of the bill event.") + type: Optional[str] = Field(default=None, description="Type of webhook event.") + created_date: Optional[str] = Field(default=None, description="The datetime in UTC of when the webhook event was produced by Codat.", alias="createdDate") + payload: Optional[BillEventPayload] = None + __properties: ClassVar[List[str]] = ["id", "type", "createdDate", "payload"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of BillEventWebhook from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of payload + if self.payload: + _dict['payload'] = self.payload.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of BillEventWebhook from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "type": obj.get("type"), + "createdDate": obj.get("createdDate"), + "payload": BillEventPayload.from_dict(obj["payload"]) if obj.get("payload") is not None else None + }) + return _obj + + + + + +class BillEventWebhookTypedDict(TypedDict): + """TypedDict variant of BillEventWebhook, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + type: NotRequired[Optional[str]] + created_date: NotRequired[Optional[str]] + payload: NotRequired[Optional[BillEventPayloadTypedDict]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/company_details.py b/sync-for-payables/src/codat_sync_for_payables/models/company_details.py new file mode 100644 index 000000000..f57e73ca2 --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/models/company_details.py @@ -0,0 +1,141 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated, NotRequired, TypedDict +from codat_sync_for_payables.models.shared.companyreference import CompanyReference, CompanyReferenceTypedDict +from typing import Optional, Set +from typing_extensions import Self + +class CompanyDetails(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + CompanyDetails + """ # noqa: E501 + id: str = Field(description="Unique identifier for your SMB in Codat.") + name: str = Field(description="The name of the company") + description: Optional[str] = Field(default=None, description="Additional information about the company. This can be used to store foreign IDs, references, etc.") + redirect: str = Field(description="The `redirect` [Link URL](https://docs.codat.io/auth-flow/authorize-hosted-link) enabling the customer to start their auth flow journey for the company.") + last_sync: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.", alias="lastSync") + created: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.") + created_by_user_name: Optional[str] = Field(default=None, description="Name of user that created the company in Codat.", alias="createdByUserName") + products: Optional[List[str]] = Field(default=None, description="An array of products that are currently enabled for the company.") + tags: Optional[Dict[str, str]] = Field(default=None, description="A collection of user-defined key-value pairs that store custom metadata against the company.") + reference_parent_company: Optional[CompanyReference] = Field(default=None, description="The parent entity or controlling organization of this company. Null if the company has no parent.", alias="referenceParentCompany") + reference_subsidiary_companies: Optional[List[CompanyReference]] = Field(default=None, description="A list of subsidiary companies owned or controlled by this entity. Empty if the company has no children.", alias="referenceSubsidiaryCompanies") + __properties: ClassVar[List[str]] = ["id", "name", "description", "redirect", "lastSync", "created", "createdByUserName", "products", "tags", "referenceParentCompany", "referenceSubsidiaryCompanies"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CompanyDetails from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of reference_parent_company + if self.reference_parent_company: + _dict['referenceParentCompany'] = self.reference_parent_company.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in reference_subsidiary_companies (list) + _items = [] + if self.reference_subsidiary_companies: + for _item_reference_subsidiary_companies in self.reference_subsidiary_companies: + if _item_reference_subsidiary_companies: + _items.append(_item_reference_subsidiary_companies.to_dict()) + _dict['referenceSubsidiaryCompanies'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CompanyDetails from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name"), + "description": obj.get("description"), + "redirect": obj.get("redirect"), + "lastSync": obj.get("lastSync"), + "created": obj.get("created"), + "createdByUserName": obj.get("createdByUserName"), + "products": obj.get("products"), + "tags": obj.get("tags"), + "referenceParentCompany": CompanyReference.from_dict(obj["referenceParentCompany"]) if obj.get("referenceParentCompany") is not None else None, + "referenceSubsidiaryCompanies": [CompanyReference.from_dict(_item) for _item in obj["referenceSubsidiaryCompanies"]] if obj.get("referenceSubsidiaryCompanies") is not None else None + }) + return _obj + + + + + +class CompanyDetailsTypedDict(TypedDict): + """TypedDict variant of CompanyDetails, for dict-literal request/response inputs.""" + id: NotRequired[str] + name: NotRequired[str] + description: NotRequired[Optional[str]] + redirect: NotRequired[str] + last_sync: NotRequired[Optional[str]] + created: NotRequired[Optional[str]] + created_by_user_name: NotRequired[Optional[str]] + products: NotRequired[Optional[List[str]]] + tags: NotRequired[Optional[Dict[str, str]]] + reference_parent_company: NotRequired[Optional[CompanyReferenceTypedDict]] + reference_subsidiary_companies: NotRequired[Optional[List[CompanyReferenceTypedDict]]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/company_reference_links.py b/sync-for-payables/src/codat_sync_for_payables/models/company_reference_links.py new file mode 100644 index 000000000..67ad31980 --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/models/company_reference_links.py @@ -0,0 +1,99 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class CompanyReferenceLinks(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + A collection of links for the company. + """ # noqa: E501 + portal: Optional[str] = Field(default=None, description="Link to the company page in the portal.") + __properties: ClassVar[List[str]] = ["portal"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CompanyReferenceLinks from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CompanyReferenceLinks from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "portal": obj.get("portal") + }) + return _obj + + + + + +class CompanyReferenceLinksTypedDict(TypedDict): + """TypedDict variant of CompanyReferenceLinks, for dict-literal request/response inputs.""" + portal: NotRequired[Optional[str]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/create_connection_request.py b/sync-for-payables/src/codat_sync_for_payables/models/create_connection_request.py new file mode 100644 index 000000000..5be6c573e --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/models/create_connection_request.py @@ -0,0 +1,110 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated, NotRequired, TypedDict +from typing import Optional, Set +from typing_extensions import Self + +class CreateConnectionRequest(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + CreateConnectionRequest + """ # noqa: E501 + platform_key: Optional[str] = Field(default=None, description="A unique 4-letter key to represent a platform in each integration. View [accounting](https://docs.codat.io/integrations/accounting/overview#platform-keys), [banking](https://docs.codat.io/integrations/banking/overview#platform-keys), and [commerce](https://docs.codat.io/integrations/commerce/overview#platform-keys) platform keys.", alias="platformKey") + __properties: ClassVar[List[str]] = ["platformKey"] + + @field_validator('platform_key') + def platform_key_validate_regular_expression(cls, value): + """Validates the regular expression""" + if value is None: + return value + + if not re.match(r"[a-z]{4}", value): + raise ValueError(r"must validate the regular expression /[a-z]{4}/") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CreateConnectionRequest from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CreateConnectionRequest from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "platformKey": obj.get("platformKey") + }) + return _obj + + + + + +class CreateConnectionRequestTypedDict(TypedDict): + """TypedDict variant of CreateConnectionRequest, for dict-literal request/response inputs.""" + platform_key: NotRequired[Optional[str]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/current_status.py b/sync-for-payables/src/codat_sync_for_payables/models/current_status.py new file mode 100644 index 000000000..5f023c517 --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/models/current_status.py @@ -0,0 +1,28 @@ +from __future__ import annotations + +from enum import Enum + + +class CurrentStatus(str, Enum): + """CurrentStatus enum (lifted from inline OAS enum).""" + INITIAL = 'Initial' + QUEUED = 'Queued' + FETCHING = 'Fetching' + MAP_QUEUED = 'MapQueued' + MAPPING = 'Mapping' + COMPLETE = 'Complete' + FETCH_ERROR = 'FetchError' + MAP_ERROR = 'MapError' + INTERNAL_ERROR = 'InternalError' + PROCESSING_QUEUED = 'ProcessingQueued' + PROCESSING = 'Processing' + PROCESSING_ERROR = 'ProcessingError' + VALIDATION_QUEUED = 'ValidationQueued' + VALIDATING = 'Validating' + VALIDATION_ERROR = 'ValidationError' + AUTH_ERROR = 'AuthError' + CANCELLED = 'Cancelled' + NOT_SUPPORTED = 'NotSupported' + RATE_LIMIT_ERROR = 'RateLimitError' + PERMISSIONS_ERROR = 'PermissionsError' + PREREQUISITE_NOT_MET = 'PrerequisiteNotMet' diff --git a/sync-for-payables/src/codat_sync_for_payables/models/data_status.py b/sync-for-payables/src/codat_sync_for_payables/models/data_status.py new file mode 100644 index 000000000..f7d427501 --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/models/data_status.py @@ -0,0 +1,127 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +from codat_sync_for_payables.models.current_status import CurrentStatus +from codat_sync_for_payables.models.data_types import DataTypes +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class DataStatus(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + Describes the state of data in the Codat cache for a company and data type + """ # noqa: E501 + data_type: str = Field(description="Available data types", alias="dataType") + last_successful_sync: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.", alias="lastSuccessfulSync") + current_status: str = Field(description="The current status of the dataset.", alias="currentStatus") + latest_sync_id: Optional[str] = Field(default=None, description="Unique identifier for most recent sync of data type.", alias="latestSyncId") + latest_successful_sync_id: Optional[str] = Field(default=None, description="Unique identifier for the most recent successful sync of data type.", alias="latestSuccessfulSyncId") + __properties: ClassVar[List[str]] = ["dataType", "lastSuccessfulSync", "currentStatus", "latestSyncId", "latestSuccessfulSyncId"] + + @field_validator('data_type') + def data_type_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['accountTransactions', 'balanceSheet', 'bankAccounts', 'bankTransactions', 'billCreditNotes', 'billPayments', 'bills', 'cashFlowStatement', 'chartOfAccounts', 'company', 'creditNotes', 'customers', 'directCosts', 'directIncomes', 'invoices', 'itemReceipts', 'items', 'journalEntries', 'journals', 'paymentMethods', 'payments', 'profitAndLoss', 'purchaseOrders', 'salesOrders', 'suppliers', 'taxRates', 'trackingCategories', 'transfers', 'banking-accountBalances', 'banking-accounts', 'banking-transactionCategories', 'banking-transactions', 'commerce-companyInfo', 'commerce-customers', 'commerce-disputes', 'commerce-locations', 'commerce-orders', 'commerce-paymentMethods', 'commerce-payments', 'commerce-productCategories', 'commerce-products', 'commerce-taxComponents', 'commerce-transactions']): + raise ValueError("must be one of enum values ('accountTransactions', 'balanceSheet', 'bankAccounts', 'bankTransactions', 'billCreditNotes', 'billPayments', 'bills', 'cashFlowStatement', 'chartOfAccounts', 'company', 'creditNotes', 'customers', 'directCosts', 'directIncomes', 'invoices', 'itemReceipts', 'items', 'journalEntries', 'journals', 'paymentMethods', 'payments', 'profitAndLoss', 'purchaseOrders', 'salesOrders', 'suppliers', 'taxRates', 'trackingCategories', 'transfers', 'banking-accountBalances', 'banking-accounts', 'banking-transactionCategories', 'banking-transactions', 'commerce-companyInfo', 'commerce-customers', 'commerce-disputes', 'commerce-locations', 'commerce-orders', 'commerce-paymentMethods', 'commerce-payments', 'commerce-productCategories', 'commerce-products', 'commerce-taxComponents', 'commerce-transactions')") + return value + + @field_validator('current_status') + def current_status_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['Initial', 'Queued', 'Fetching', 'MapQueued', 'Mapping', 'Complete', 'FetchError', 'MapError', 'InternalError', 'ProcessingQueued', 'Processing', 'ProcessingError', 'ValidationQueued', 'Validating', 'ValidationError', 'AuthError', 'Cancelled', 'NotSupported', 'RateLimitError', 'PermissionsError', 'PrerequisiteNotMet']): + raise ValueError("must be one of enum values ('Initial', 'Queued', 'Fetching', 'MapQueued', 'Mapping', 'Complete', 'FetchError', 'MapError', 'InternalError', 'ProcessingQueued', 'Processing', 'ProcessingError', 'ValidationQueued', 'Validating', 'ValidationError', 'AuthError', 'Cancelled', 'NotSupported', 'RateLimitError', 'PermissionsError', 'PrerequisiteNotMet')") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of DataStatus from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of DataStatus from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "dataType": obj.get("dataType"), + "lastSuccessfulSync": obj.get("lastSuccessfulSync"), + "currentStatus": obj.get("currentStatus"), + "latestSyncId": obj.get("latestSyncId"), + "latestSuccessfulSyncId": obj.get("latestSuccessfulSyncId") + }) + return _obj + + + + + +class DataStatusTypedDict(TypedDict): + """TypedDict variant of DataStatus, for dict-literal request/response inputs.""" + data_type: NotRequired[str] + last_successful_sync: NotRequired[Optional[str]] + current_status: NotRequired[str] + latest_sync_id: NotRequired[Optional[str]] + latest_successful_sync_id: NotRequired[Optional[str]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/data_type.py b/sync-for-payables/src/codat_sync_for_payables/models/data_type.py new file mode 100644 index 000000000..2de8fab95 --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/models/data_type.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class DataType(str, Enum): + """ + Available data types + """ + + """ + allowed enum values + """ + CUSTOMERS = 'customers' + TRACKING_CATEGORIES = 'trackingCategories' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of DataType from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sync-for-payables/src/codat_sync_for_payables/models/data_types.py b/sync-for-payables/src/codat_sync_for_payables/models/data_types.py new file mode 100644 index 000000000..734060127 --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/models/data_types.py @@ -0,0 +1,50 @@ +from __future__ import annotations + +from enum import Enum + + +class DataTypes(str, Enum): + """DataTypes enum (lifted from inline OAS enum).""" + ACCOUNT_TRANSACTIONS = 'accountTransactions' + BALANCE_SHEET = 'balanceSheet' + BANK_ACCOUNTS = 'bankAccounts' + BANK_TRANSACTIONS = 'bankTransactions' + BILL_CREDIT_NOTES = 'billCreditNotes' + BILL_PAYMENTS = 'billPayments' + BILLS = 'bills' + CASH_FLOW_STATEMENT = 'cashFlowStatement' + CHART_OF_ACCOUNTS = 'chartOfAccounts' + COMPANY = 'company' + CREDIT_NOTES = 'creditNotes' + CUSTOMERS = 'customers' + DIRECT_COSTS = 'directCosts' + DIRECT_INCOMES = 'directIncomes' + INVOICES = 'invoices' + ITEM_RECEIPTS = 'itemReceipts' + ITEMS = 'items' + JOURNAL_ENTRIES = 'journalEntries' + JOURNALS = 'journals' + PAYMENT_METHODS = 'paymentMethods' + PAYMENTS = 'payments' + PROFIT_AND_LOSS = 'profitAndLoss' + PURCHASE_ORDERS = 'purchaseOrders' + SALES_ORDERS = 'salesOrders' + SUPPLIERS = 'suppliers' + TAX_RATES = 'taxRates' + TRACKING_CATEGORIES = 'trackingCategories' + TRANSFERS = 'transfers' + BANKING_ACCOUNT_BALANCES = 'banking-accountBalances' + BANKING_ACCOUNTS = 'banking-accounts' + BANKING_TRANSACTION_CATEGORIES = 'banking-transactionCategories' + BANKING_TRANSACTIONS = 'banking-transactions' + COMMERCE_COMPANY_INFO = 'commerce-companyInfo' + COMMERCE_CUSTOMERS = 'commerce-customers' + COMMERCE_DISPUTES = 'commerce-disputes' + COMMERCE_LOCATIONS = 'commerce-locations' + COMMERCE_ORDERS = 'commerce-orders' + COMMERCE_PAYMENT_METHODS = 'commerce-paymentMethods' + COMMERCE_PAYMENTS = 'commerce-payments' + COMMERCE_PRODUCT_CATEGORIES = 'commerce-productCategories' + COMMERCE_PRODUCTS = 'commerce-products' + COMMERCE_TAX_COMPONENTS = 'commerce-taxComponents' + COMMERCE_TRANSACTIONS = 'commerce-transactions' diff --git a/sync-for-payables/src/codat_sync_for_payables/models/dataset_status.py b/sync-for-payables/src/codat_sync_for_payables/models/dataset_status.py new file mode 100644 index 000000000..2b657c709 --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/models/dataset_status.py @@ -0,0 +1,28 @@ +from __future__ import annotations + +from enum import Enum + + +class DatasetStatus(str, Enum): + """DatasetStatus enum (lifted from inline OAS enum).""" + INITIAL = 'Initial' + QUEUED = 'Queued' + FETCHING = 'Fetching' + MAP_QUEUED = 'MapQueued' + MAPPING = 'Mapping' + COMPLETE = 'Complete' + FETCH_ERROR = 'FetchError' + MAP_ERROR = 'MapError' + INTERNAL_ERROR = 'InternalError' + PROCESSING_QUEUED = 'ProcessingQueued' + PROCESSING = 'Processing' + PROCESSING_ERROR = 'ProcessingError' + VALIDATION_QUEUED = 'ValidationQueued' + VALIDATING = 'Validating' + VALIDATION_ERROR = 'ValidationError' + AUTH_ERROR = 'AuthError' + CANCELLED = 'Cancelled' + NOT_SUPPORTED = 'NotSupported' + RATE_LIMIT_ERROR = 'RateLimitError' + PERMISSIONS_ERROR = 'PermissionsError' + PREREQUISITE_NOT_MET = 'PrerequisiteNotMet' diff --git a/sync-for-payables/src/codat_sync_for_payables/models/error_message.py b/sync-for-payables/src/codat_sync_for_payables/models/error_message.py new file mode 100644 index 000000000..3ff641f10 --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/models/error_message.py @@ -0,0 +1,121 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_sync_for_payables.models.shared.errorvalidation import ErrorValidation, ErrorValidationTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class ErrorMessage(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + ErrorMessage + """ # noqa: E501 + status_code: Optional[int] = Field(default=None, description="The HTTP status code returned by the error.", alias="statusCode") + service: Optional[str] = Field(default=None, description="Codat's service the returned the error.") + error: Optional[str] = Field(default=None, description="A brief description of the error.") + correlation_id: Optional[str] = Field(default=None, description="Unique identifier used to propagate to all downstream services and determine the source of the error.", alias="correlationId") + validation: Optional[ErrorValidation] = None + can_be_retried: Optional[str] = Field(default=None, description="`True` if the error occurred transiently and can be retried.", alias="canBeRetried") + detailed_error_code: Optional[int] = Field(default=None, description="Machine readable error code used to automate processes based on the code returned.", alias="detailedErrorCode") + __properties: ClassVar[List[str]] = ["statusCode", "service", "error", "correlationId", "validation", "canBeRetried", "detailedErrorCode"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ErrorMessage from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of validation + if self.validation: + _dict['validation'] = self.validation.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ErrorMessage from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "statusCode": obj.get("statusCode"), + "service": obj.get("service"), + "error": obj.get("error"), + "correlationId": obj.get("correlationId"), + "validation": ErrorValidation.from_dict(obj["validation"]) if obj.get("validation") is not None else None, + "canBeRetried": obj.get("canBeRetried"), + "detailedErrorCode": obj.get("detailedErrorCode") + }) + return _obj + + + + + +class ErrorMessageTypedDict(TypedDict): + """TypedDict variant of ErrorMessage, for dict-literal request/response inputs.""" + status_code: NotRequired[Optional[int]] + service: NotRequired[Optional[str]] + error: NotRequired[Optional[str]] + correlation_id: NotRequired[Optional[str]] + validation: NotRequired[Optional[ErrorValidationTypedDict]] + can_be_retried: NotRequired[Optional[str]] + detailed_error_code: NotRequired[Optional[int]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/error_status.py b/sync-for-payables/src/codat_sync_for_payables/models/error_status.py new file mode 100644 index 000000000..ecf0a01b7 --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/models/error_status.py @@ -0,0 +1,9 @@ +from __future__ import annotations + +from enum import Enum + + +class ErrorStatus(str, Enum): + """ErrorStatus enum (lifted from inline OAS enum).""" + ACTIVE = 'Active' + RESOLVED = 'Resolved' diff --git a/sync-for-payables/src/codat_sync_for_payables/models/errors/__init__.py b/sync-for-payables/src/codat_sync_for_payables/models/errors/__init__.py index 709ea11be..c6cccc0f6 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/errors/__init__.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/errors/__init__.py @@ -1,39 +1,16 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.models.errors — Speakeasy-shape exception hierarchy.""" from .codatsyncpayableserror import CodatSyncPayablesError -from typing import Any, TYPE_CHECKING - -from codat_sync_for_payables.utils.dynamic_imports import lazy_getattr, lazy_dir - -if TYPE_CHECKING: - from .errormessage import ErrorMessage, ErrorMessageData - from .no_response_error import NoResponseError - from .responsevalidationerror import ResponseValidationError - from .sdkerror import SDKError +from .sdkerror import SDKError +from .errormessage import ErrorMessage, ErrorMessageData +from .no_response_error import NoResponseError +from .responsevalidationerror import ResponseValidationError __all__ = [ "CodatSyncPayablesError", + "SDKError", "ErrorMessage", "ErrorMessageData", "NoResponseError", "ResponseValidationError", - "SDKError", ] - -_dynamic_imports: dict[str, str] = { - "ErrorMessage": ".errormessage", - "ErrorMessageData": ".errormessage", - "NoResponseError": ".no_response_error", - "ResponseValidationError": ".responsevalidationerror", - "SDKError": ".sdkerror", -} - - -def __getattr__(attr_name: str) -> Any: - return lazy_getattr( - attr_name, package=__package__, dynamic_imports=_dynamic_imports - ) - - -def __dir__(): - return lazy_dir(dynamic_imports=_dynamic_imports) diff --git a/sync-for-payables/src/codat_sync_for_payables/models/errors/codatsyncpayableserror.py b/sync-for-payables/src/codat_sync_for_payables/models/errors/codatsyncpayableserror.py index eb8a5afe0..02656c5c3 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/errors/codatsyncpayableserror.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/errors/codatsyncpayableserror.py @@ -1,30 +1,72 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""Base error class for codat_sync_for_payables. -import httpx -from typing import Optional +Generated by pipeline/postprocess_generated.py — do not edit by hand. +""" + +from __future__ import annotations + +from collections.abc import Mapping as _AbcMapping from dataclasses import dataclass, field +from typing import Any, Iterator, Mapping, Optional + + +class CaseInsensitiveHeaders(_AbcMapping): + """Read-only header mapping with case-insensitive lookup, matching the + httpx.Headers a Speakeasy consumer reads. urllib3 hands the POC original-case + keys, so `err.headers["content-type"]` would miss a `Content-Type` header on a + plain dict; here keys are stored lower-cased and lookups are lower-cased too, so + exact-, lower- and mixed-case lookups all match and iteration yields lower-case + keys, exactly as httpx.Headers does.""" + + def __init__(self, data: Optional[Mapping[str, str]] = None) -> None: + self._store = {str(k).lower(): v for k, v in dict(data or {}).items()} + + def __getitem__(self, key: str) -> str: + return self._store[str(key).lower()] + + def __iter__(self) -> Iterator[str]: + return iter(self._store) + + def __len__(self) -> int: + return len(self._store) + + def __repr__(self) -> str: + return f"CaseInsensitiveHeaders({self._store!r})" @dataclass(unsafe_hash=True) class CodatSyncPayablesError(Exception): - """The base class for all HTTP error responses.""" + """The base class for all SDK errors.""" message: str - status_code: int - body: str - headers: httpx.Headers = field(hash=False) - raw_response: httpx.Response = field(hash=False) + status_code: int = 0 + body: str = "" + headers: Mapping[str, str] = field(default_factory=dict, hash=False) + raw_response: Optional[Any] = field(default=None, hash=False) def __init__( - self, message: str, raw_response: httpx.Response, body: Optional[str] = None - ): + self, + message: str, + raw_response: Optional[Any] = None, + body: Optional[str] = None, + status_code: Optional[int] = None, + headers: Optional[Mapping[str, str]] = None, + ) -> None: + # `raw_response` is the 2nd positional arg to match Speakeasy + # (`CodatSyncPayablesError(message, raw_response, body)`). status_code / body / + # headers are derived from raw_response when not passed explicitly. + if status_code is None: + status_code = getattr(raw_response, "status_code", None) or getattr(raw_response, "status", None) or 0 + if body is None: + body = (getattr(raw_response, "text", "") if raw_response is not None else "") or "" + if headers is None: + headers = getattr(raw_response, "headers", None) object.__setattr__(self, "message", message) - object.__setattr__(self, "status_code", raw_response.status_code) - object.__setattr__( - self, "body", body if body is not None else raw_response.text - ) - object.__setattr__(self, "headers", raw_response.headers) + object.__setattr__(self, "status_code", status_code) + object.__setattr__(self, "body", body or "") + object.__setattr__(self, "headers", CaseInsensitiveHeaders(headers)) object.__setattr__(self, "raw_response", raw_response) + super().__init__(message) - def __str__(self): + def __str__(self) -> str: return self.message diff --git a/sync-for-payables/src/codat_sync_for_payables/models/errors/errormessage.py b/sync-for-payables/src/codat_sync_for_payables/models/errors/errormessage.py index 5e15ab951..c2a564bf6 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/errors/errormessage.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/errors/errormessage.py @@ -1,53 +1,41 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""ErrorMessage — typed exception raised for structured Codat API errors. + +Raised when an HTTP response body parses against the ErrorMessage schema +(i.e. Codat-shaped error envelopes with correlationId, statusCode, etc.). +""" from __future__ import annotations -from codat_sync_for_payables.models.errors import CodatSyncPayablesError -from codat_sync_for_payables.models.shared import ( - errorvalidation as shared_errorvalidation, -) -from codat_sync_for_payables.types import BaseModel, OptionalNullable, UNSET -from dataclasses import dataclass, field -import httpx -import pydantic -from typing import Optional -from typing_extensions import Annotated - - -class ErrorMessageData(BaseModel): - status_code: Annotated[Optional[int], pydantic.Field(alias="statusCode")] = None - r"""The HTTP status code returned by the error.""" - service: Optional[str] = None - r"""Codat's service the returned the error.""" - error: Optional[str] = None - r"""A brief description of the error.""" - correlation_id: Annotated[Optional[str], pydantic.Field(alias="correlationId")] = ( - None - ) - r"""Unique identifier used to propagate to all downstream services and determine the source of the error.""" - validation: OptionalNullable[shared_errorvalidation.ErrorValidation] = UNSET - r"""A human-readable object describing validation decisions Codat has made. If an operation has failed because of validation errors, they will be detailed here.""" - can_be_retried: Annotated[Optional[str], pydantic.Field(alias="canBeRetried")] = ( - None - ) - r"""`True` if the error occurred transiently and can be retried.""" - detailed_error_code: Annotated[ - Optional[int], pydantic.Field(alias="detailedErrorCode") - ] = None - r"""Machine readable error code used to automate processes based on the code returned.""" - - -@dataclass(unsafe_hash=True) + +from typing import Any, Mapping, Optional + +from .codatsyncpayableserror import CodatSyncPayablesError +from codat_sync_for_payables.models.error_message import ErrorMessage as ErrorMessageData + + class ErrorMessage(CodatSyncPayablesError): - r"""Your `query` parameter was not correctly formed""" + """Typed Codat API error response. Access structured fields via `.data`.""" - data: ErrorMessageData = field(hash=False) + data: ErrorMessageData def __init__( self, data: ErrorMessageData, - raw_response: httpx.Response, + raw_response: Optional[Any] = None, body: Optional[str] = None, - ): - message = body or raw_response.text - super().__init__(message, raw_response, body) - object.__setattr__(self, "data", data) + status_code: Optional[int] = None, + headers: Optional[Mapping[str, str]] = None, + ) -> None: + # `raw_response` is the 2nd positional arg to match Speakeasy + # (`ErrorMessage(data, raw_response, body)`). + message = body or str(data) + super().__init__( + message, + raw_response=raw_response, + body=body, + status_code=status_code, + headers=headers, + ) + self.data = data + + +__all__ = ["ErrorMessage", "ErrorMessageData"] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/errors/no_response_error.py b/sync-for-payables/src/codat_sync_for_payables/models/errors/no_response_error.py index 1deab64bc..acea02af8 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/errors/no_response_error.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/errors/no_response_error.py @@ -1,4 +1,6 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""NoResponseError — raised when the HTTP client never receives a response (timeout, dropped connection, DNS failure).""" + +from __future__ import annotations from dataclasses import dataclass @@ -9,9 +11,12 @@ class NoResponseError(Exception): message: str - def __init__(self, message: str = "No response received"): + def __init__(self, message: str = "No response received") -> None: object.__setattr__(self, "message", message) super().__init__(message) - def __str__(self): + def __str__(self) -> str: return self.message + + +__all__ = ["NoResponseError"] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/errors/responsevalidationerror.py b/sync-for-payables/src/codat_sync_for_payables/models/errors/responsevalidationerror.py index d6e2f035e..22044b18c 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/errors/responsevalidationerror.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/errors/responsevalidationerror.py @@ -1,27 +1,42 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""ResponseValidationError — raised when a successful HTTP response body cannot be parsed against the expected response model.""" -import httpx -from typing import Optional -from dataclasses import dataclass +from __future__ import annotations -from codat_sync_for_payables.models.errors import CodatSyncPayablesError +from typing import Any, Mapping, Optional + +from .codatsyncpayableserror import CodatSyncPayablesError -@dataclass(unsafe_hash=True) class ResponseValidationError(CodatSyncPayablesError): - """Error raised when there is a type mismatch between the response data and the expected Pydantic model.""" + """Raised on a pydantic ValidationError when deserialising a Codat response body.""" def __init__( self, message: str, - raw_response: httpx.Response, - cause: Exception, - body: Optional[str] = None, - ): - message = f"{message}: {cause}" - super().__init__(message, raw_response, body) + raw_response: Optional[Any] = None, + cause: Optional[Exception] = None, + body: str = "", + status_code: Optional[int] = None, + headers: Optional[Mapping[str, str]] = None, + ) -> None: + # `raw_response` is the 2nd positional arg, `cause` the 3rd, to match + # Speakeasy (`ResponseValidationError(message, raw_response, cause, body)`). + full_message = f"{message}: {cause}" + super().__init__( + full_message, + raw_response=raw_response, + body=body, + status_code=status_code, + headers=headers, + ) + # Surface the underlying pydantic ValidationError via the standard `__cause__` mechanism + # so callers can do `except errors.ResponseValidationError as e: print(e.cause)`. + self.__cause__ = cause @property - def cause(self): - """Normally the Pydantic ValidationError""" + def cause(self) -> Optional[BaseException]: + """Normally the underlying pydantic ValidationError.""" return self.__cause__ + + +__all__ = ["ResponseValidationError"] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/errors/sdkerror.py b/sync-for-payables/src/codat_sync_for_payables/models/errors/sdkerror.py index a23569a5b..cc6455f91 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/errors/sdkerror.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/errors/sdkerror.py @@ -1,40 +1,39 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""SDKError — fallback exception for any HTTP error.""" -import httpx -from typing import Optional -from dataclasses import dataclass +from __future__ import annotations + +from typing import Any, Mapping, Optional + +from .codatsyncpayableserror import CodatSyncPayablesError -from codat_sync_for_payables.models.errors import CodatSyncPayablesError MAX_MESSAGE_LEN = 10_000 -@dataclass(unsafe_hash=True) class SDKError(CodatSyncPayablesError): """The fallback error class if no more specific error class is matched.""" def __init__( - self, message: str, raw_response: httpx.Response, body: Optional[str] = None - ): - body_display = body or raw_response.text or '""' - + self, + message: str, + raw_response: Optional[Any] = None, + body: Optional[str] = None, + status_code: Optional[int] = None, + headers: Optional[Mapping[str, str]] = None, + ) -> None: + # `raw_response` is the 2nd positional arg to match Speakeasy + # (`SDKError(message, raw_response, body)`); existing consumer code that + # re-raises via `SDKError(msg, response)` then stores the response in + # `raw_response`, not `status_code`. status_code / body are derived from + # raw_response when not passed explicitly. + if status_code is None: + status_code = getattr(raw_response, "status_code", None) or getattr(raw_response, "status", None) or 0 + body_display = body or (getattr(raw_response, "text", "") if raw_response is not None else "") or "" if message: message += ": " - message += f"Status {raw_response.status_code}" - - headers = raw_response.headers - content_type = headers.get("content-type", '""') - if content_type != "application/json": - if " " in content_type: - content_type = f'"{content_type}"' - message += f" Content-Type {content_type}" - - if len(body_display) > MAX_MESSAGE_LEN: - truncated = body_display[:MAX_MESSAGE_LEN] - remaining = len(body_display) - MAX_MESSAGE_LEN - body_display = f"{truncated}...and {remaining} more chars" - - message += f". Body: {body_display}" - message = message.strip() - - super().__init__(message, raw_response, body) + message += f"Status {status_code}" + if body_display: + if len(body_display) > MAX_MESSAGE_LEN: + body_display = body_display[:MAX_MESSAGE_LEN] + f"...and {len(body_display) - MAX_MESSAGE_LEN} more chars" + message += f". Body: {body_display}" + super().__init__(message.strip(), status_code=status_code, body=body or "", headers=headers, raw_response=raw_response) diff --git a/sync-for-payables/src/codat_sync_for_payables/models/operations/__init__.py b/sync-for-payables/src/codat_sync_for_payables/models/operations/__init__.py index acb9ce509..718d3f7e4 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/operations/__init__.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/operations/__init__.py @@ -1,191 +1,74 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.models.operations — re-exports of per-operation request envelopes.""" -from typing import Any, TYPE_CHECKING +from codat_sync_for_payables.api.bank_accounts import ( + CreateBankAccountRequest, + CreateBankAccountRequestTypedDict, +) +from codat_sync_for_payables.api.bill_payments import ( + CreateBillPaymentRequest, + CreateBillPaymentRequestTypedDict, + GetMappingOptionsPaymentsRequest, + GetMappingOptionsPaymentsRequestTypedDict, +) +from codat_sync_for_payables.api.bills import ( + CreateBillRequest, + CreateBillRequestTypedDict, + DownloadBillAttachmentRequest, + DownloadBillAttachmentRequestTypedDict, + GetMappingOptionsBillsRequest, + GetMappingOptionsBillsRequestTypedDict, + ListBillAttachmentsRequest, + ListBillAttachmentsRequestTypedDict, + ListBillsRequest, + ListBillsRequestTypedDict, + UpdateBillRequest, + UpdateBillRequestTypedDict, + UploadBillAttachmentRequest, + UploadBillAttachmentRequestTypedDict, +) +from codat_sync_for_payables.api.companies import ( + CreateCompanyRequest, + CreateCompanyRequestTypedDict, + DeleteCompanyRequest, + DeleteCompanyRequestTypedDict, + GetCompanyRequest, + GetCompanyRequestTypedDict, + ListCompaniesRequest, + ListCompaniesRequestTypedDict, + ReplaceCompanyRequest, + ReplaceCompanyRequestTypedDict, + UpdateCompanyRequest, + UpdateCompanyRequestTypedDict, +) +from codat_sync_for_payables.api.company_information import ( + GetCompanyInformationRequest, + GetCompanyInformationRequestTypedDict, +) +from codat_sync_for_payables.api.connections import ( + CreateConnectionRequest, + CreateConnectionRequestTypedDict, + DeleteConnectionRequest, + DeleteConnectionRequestTypedDict, + GetConnectionRequest, + GetConnectionRequestTypedDict, + ListConnectionsRequest, + ListConnectionsRequestTypedDict, + UnlinkConnectionRequest, + UnlinkConnectionRequestTypedDict, +) +from codat_sync_for_payables.api.suppliers import ( + CreateSupplierRequest, + CreateSupplierRequestTypedDict, + ListSuppliersRequest, + ListSuppliersRequestTypedDict, + UpdateSupplierRequest, + UpdateSupplierRequestTypedDict, +) -from codat_sync_for_payables.utils.dynamic_imports import lazy_getattr, lazy_dir +# Speakeasy request-body class names (aliases to POC body classes). +from codat_sync_for_payables.models.create_connection_request import CreateConnectionRequest as CreateConnectionRequestBody +from codat_sync_for_payables.models.update_connection import UpdateConnection as UnlinkConnectionUpdateConnection -if TYPE_CHECKING: - from .create_bank_account import ( - CreateBankAccountRequest, - CreateBankAccountRequestTypedDict, - ) - from .create_bill import CreateBillRequest, CreateBillRequestTypedDict - from .create_bill_payment import ( - CreateBillPaymentRequest, - CreateBillPaymentRequestTypedDict, - ) - from .create_connection import ( - CreateConnectionRequest, - CreateConnectionRequestBody, - CreateConnectionRequestBodyTypedDict, - CreateConnectionRequestTypedDict, - ) - from .create_supplier import CreateSupplierRequest, CreateSupplierRequestTypedDict - from .delete_company import DeleteCompanyRequest, DeleteCompanyRequestTypedDict - from .delete_connection import ( - DeleteConnectionRequest, - DeleteConnectionRequestTypedDict, - ) - from .download_bill_attachment import ( - DownloadBillAttachmentRequest, - DownloadBillAttachmentRequestTypedDict, - ) - from .get_company import GetCompanyRequest, GetCompanyRequestTypedDict - from .get_company_information import ( - GetCompanyInformationRequest, - GetCompanyInformationRequestTypedDict, - ) - from .get_connection import GetConnectionRequest, GetConnectionRequestTypedDict - from .get_mapping_options_bills import ( - GetMappingOptionsBillsRequest, - GetMappingOptionsBillsRequestTypedDict, - ) - from .get_mapping_options_payments import ( - GetMappingOptionsPaymentsRequest, - GetMappingOptionsPaymentsRequestTypedDict, - ) - from .list_bill_attachments import ( - ListBillAttachmentsRequest, - ListBillAttachmentsRequestTypedDict, - ) - from .list_bills import ListBillsRequest, ListBillsRequestTypedDict - from .list_companies import ListCompaniesRequest, ListCompaniesRequestTypedDict - from .list_connections import ( - ListConnectionsRequest, - ListConnectionsRequestTypedDict, - ) - from .list_suppliers import ListSuppliersRequest, ListSuppliersRequestTypedDict - from .replace_company import ReplaceCompanyRequest, ReplaceCompanyRequestTypedDict - from .unlink_connection import ( - UnlinkConnectionRequest, - UnlinkConnectionRequestTypedDict, - UnlinkConnectionUpdateConnection, - UnlinkConnectionUpdateConnectionTypedDict, - ) - from .update_bill import UpdateBillRequest, UpdateBillRequestTypedDict - from .update_company import UpdateCompanyRequest, UpdateCompanyRequestTypedDict - from .update_supplier import UpdateSupplierRequest, UpdateSupplierRequestTypedDict - from .upload_bill_attachment import ( - UploadBillAttachmentRequest, - UploadBillAttachmentRequestTypedDict, - ) - -__all__ = [ - "CreateBankAccountRequest", - "CreateBankAccountRequestTypedDict", - "CreateBillPaymentRequest", - "CreateBillPaymentRequestTypedDict", - "CreateBillRequest", - "CreateBillRequestTypedDict", - "CreateConnectionRequest", - "CreateConnectionRequestBody", - "CreateConnectionRequestBodyTypedDict", - "CreateConnectionRequestTypedDict", - "CreateSupplierRequest", - "CreateSupplierRequestTypedDict", - "DeleteCompanyRequest", - "DeleteCompanyRequestTypedDict", - "DeleteConnectionRequest", - "DeleteConnectionRequestTypedDict", - "DownloadBillAttachmentRequest", - "DownloadBillAttachmentRequestTypedDict", - "GetCompanyInformationRequest", - "GetCompanyInformationRequestTypedDict", - "GetCompanyRequest", - "GetCompanyRequestTypedDict", - "GetConnectionRequest", - "GetConnectionRequestTypedDict", - "GetMappingOptionsBillsRequest", - "GetMappingOptionsBillsRequestTypedDict", - "GetMappingOptionsPaymentsRequest", - "GetMappingOptionsPaymentsRequestTypedDict", - "ListBillAttachmentsRequest", - "ListBillAttachmentsRequestTypedDict", - "ListBillsRequest", - "ListBillsRequestTypedDict", - "ListCompaniesRequest", - "ListCompaniesRequestTypedDict", - "ListConnectionsRequest", - "ListConnectionsRequestTypedDict", - "ListSuppliersRequest", - "ListSuppliersRequestTypedDict", - "ReplaceCompanyRequest", - "ReplaceCompanyRequestTypedDict", - "UnlinkConnectionRequest", - "UnlinkConnectionRequestTypedDict", - "UnlinkConnectionUpdateConnection", - "UnlinkConnectionUpdateConnectionTypedDict", - "UpdateBillRequest", - "UpdateBillRequestTypedDict", - "UpdateCompanyRequest", - "UpdateCompanyRequestTypedDict", - "UpdateSupplierRequest", - "UpdateSupplierRequestTypedDict", - "UploadBillAttachmentRequest", - "UploadBillAttachmentRequestTypedDict", -] - -_dynamic_imports: dict[str, str] = { - "CreateBankAccountRequest": ".create_bank_account", - "CreateBankAccountRequestTypedDict": ".create_bank_account", - "CreateBillRequest": ".create_bill", - "CreateBillRequestTypedDict": ".create_bill", - "CreateBillPaymentRequest": ".create_bill_payment", - "CreateBillPaymentRequestTypedDict": ".create_bill_payment", - "CreateConnectionRequest": ".create_connection", - "CreateConnectionRequestBody": ".create_connection", - "CreateConnectionRequestBodyTypedDict": ".create_connection", - "CreateConnectionRequestTypedDict": ".create_connection", - "CreateSupplierRequest": ".create_supplier", - "CreateSupplierRequestTypedDict": ".create_supplier", - "DeleteCompanyRequest": ".delete_company", - "DeleteCompanyRequestTypedDict": ".delete_company", - "DeleteConnectionRequest": ".delete_connection", - "DeleteConnectionRequestTypedDict": ".delete_connection", - "DownloadBillAttachmentRequest": ".download_bill_attachment", - "DownloadBillAttachmentRequestTypedDict": ".download_bill_attachment", - "GetCompanyRequest": ".get_company", - "GetCompanyRequestTypedDict": ".get_company", - "GetCompanyInformationRequest": ".get_company_information", - "GetCompanyInformationRequestTypedDict": ".get_company_information", - "GetConnectionRequest": ".get_connection", - "GetConnectionRequestTypedDict": ".get_connection", - "GetMappingOptionsBillsRequest": ".get_mapping_options_bills", - "GetMappingOptionsBillsRequestTypedDict": ".get_mapping_options_bills", - "GetMappingOptionsPaymentsRequest": ".get_mapping_options_payments", - "GetMappingOptionsPaymentsRequestTypedDict": ".get_mapping_options_payments", - "ListBillAttachmentsRequest": ".list_bill_attachments", - "ListBillAttachmentsRequestTypedDict": ".list_bill_attachments", - "ListBillsRequest": ".list_bills", - "ListBillsRequestTypedDict": ".list_bills", - "ListCompaniesRequest": ".list_companies", - "ListCompaniesRequestTypedDict": ".list_companies", - "ListConnectionsRequest": ".list_connections", - "ListConnectionsRequestTypedDict": ".list_connections", - "ListSuppliersRequest": ".list_suppliers", - "ListSuppliersRequestTypedDict": ".list_suppliers", - "ReplaceCompanyRequest": ".replace_company", - "ReplaceCompanyRequestTypedDict": ".replace_company", - "UnlinkConnectionRequest": ".unlink_connection", - "UnlinkConnectionRequestTypedDict": ".unlink_connection", - "UnlinkConnectionUpdateConnection": ".unlink_connection", - "UnlinkConnectionUpdateConnectionTypedDict": ".unlink_connection", - "UpdateBillRequest": ".update_bill", - "UpdateBillRequestTypedDict": ".update_bill", - "UpdateCompanyRequest": ".update_company", - "UpdateCompanyRequestTypedDict": ".update_company", - "UpdateSupplierRequest": ".update_supplier", - "UpdateSupplierRequestTypedDict": ".update_supplier", - "UploadBillAttachmentRequest": ".upload_bill_attachment", - "UploadBillAttachmentRequestTypedDict": ".upload_bill_attachment", -} - - -def __getattr__(attr_name: str) -> Any: - return lazy_getattr( - attr_name, package=__package__, dynamic_imports=_dynamic_imports - ) - - -def __dir__(): - return lazy_dir(dynamic_imports=_dynamic_imports) +# Speakeasy TypedDict companions for aliased names. +from codat_sync_for_payables.models.create_connection_request import CreateConnectionRequestTypedDict as CreateConnectionRequestBodyTypedDict +from codat_sync_for_payables.models.update_connection import UpdateConnectionTypedDict as UnlinkConnectionUpdateConnectionTypedDict diff --git a/sync-for-payables/src/codat_sync_for_payables/models/operations/create_bank_account.py b/sync-for-payables/src/codat_sync_for_payables/models/operations/create_bank_account.py index 741ff5784..5427b64e8 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/operations/create_bank_account.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/operations/create_bank_account.py @@ -1,73 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.models.operations.create_bank_account — re-export of the create_bank_account operation envelope.""" -from __future__ import annotations -from codat_sync_for_payables.models.shared import ( - bankaccountprototype as shared_bankaccountprototype, -) -from codat_sync_for_payables.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_payables.utils import ( - FieldMetadata, - HeaderMetadata, - PathParamMetadata, - RequestMetadata, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class CreateBankAccountRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - connection_id: str - r"""Unique identifier for a connection.""" - idempotency_key: NotRequired[str] - r"""A unique identifier to ensure idempotent behaviour for subsequent requests.""" - bank_account_prototype: NotRequired[ - shared_bankaccountprototype.BankAccountPrototypeTypedDict - ] - - -class CreateBankAccountRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - connection_id: Annotated[ - str, - pydantic.Field(alias="connectionId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a connection.""" - - idempotency_key: Annotated[ - Optional[str], - pydantic.Field(alias="Idempotency-Key"), - FieldMetadata(header=HeaderMetadata(style="simple", explode=False)), - ] = None - r"""A unique identifier to ensure idempotent behaviour for subsequent requests.""" - - bank_account_prototype: Annotated[ - Optional[shared_bankaccountprototype.BankAccountPrototype], - FieldMetadata(request=RequestMetadata(media_type="application/json")), - ] = None - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["Idempotency-Key", "bankAccountPrototype"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m +from codat_sync_for_payables.api.bank_accounts import CreateBankAccountRequest +from codat_sync_for_payables.api.bank_accounts import CreateBankAccountRequestTypedDict diff --git a/sync-for-payables/src/codat_sync_for_payables/models/operations/create_bill.py b/sync-for-payables/src/codat_sync_for_payables/models/operations/create_bill.py index 55577c0de..0a2bf30e0 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/operations/create_bill.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/operations/create_bill.py @@ -1,69 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.models.operations.create_bill — re-export of the create_bill operation envelope.""" -from __future__ import annotations -from codat_sync_for_payables.models.shared import billprototype as shared_billprototype -from codat_sync_for_payables.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_payables.utils import ( - FieldMetadata, - HeaderMetadata, - PathParamMetadata, - RequestMetadata, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class CreateBillRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - connection_id: str - r"""Unique identifier for a connection.""" - idempotency_key: NotRequired[str] - r"""A unique identifier to ensure idempotent behaviour for subsequent requests.""" - bill_prototype: NotRequired[shared_billprototype.BillPrototypeTypedDict] - - -class CreateBillRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - connection_id: Annotated[ - str, - pydantic.Field(alias="connectionId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a connection.""" - - idempotency_key: Annotated[ - Optional[str], - pydantic.Field(alias="Idempotency-Key"), - FieldMetadata(header=HeaderMetadata(style="simple", explode=False)), - ] = None - r"""A unique identifier to ensure idempotent behaviour for subsequent requests.""" - - bill_prototype: Annotated[ - Optional[shared_billprototype.BillPrototype], - FieldMetadata(request=RequestMetadata(media_type="application/json")), - ] = None - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["Idempotency-Key", "billPrototype"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m +from codat_sync_for_payables.api.bills import CreateBillRequest +from codat_sync_for_payables.api.bills import CreateBillRequestTypedDict diff --git a/sync-for-payables/src/codat_sync_for_payables/models/operations/create_bill_payment.py b/sync-for-payables/src/codat_sync_for_payables/models/operations/create_bill_payment.py index 1873ae4d7..18f7240e0 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/operations/create_bill_payment.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/operations/create_bill_payment.py @@ -1,82 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.models.operations.create_bill_payment — re-export of the create_bill_payment operation envelope.""" -from __future__ import annotations -from codat_sync_for_payables.models.shared import ( - billpaymentprototype as shared_billpaymentprototype, -) -from codat_sync_for_payables.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_payables.utils import ( - FieldMetadata, - HeaderMetadata, - PathParamMetadata, - RequestMetadata, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class CreateBillPaymentRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - connection_id: str - r"""Unique identifier for a connection.""" - bill_id: str - r"""Unique identifier for a bill.""" - idempotency_key: NotRequired[str] - r"""A unique identifier to ensure idempotent behaviour for subsequent requests.""" - bill_payment_prototype: NotRequired[ - shared_billpaymentprototype.BillPaymentPrototypeTypedDict - ] - - -class CreateBillPaymentRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - connection_id: Annotated[ - str, - pydantic.Field(alias="connectionId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a connection.""" - - bill_id: Annotated[ - str, - pydantic.Field(alias="billId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a bill.""" - - idempotency_key: Annotated[ - Optional[str], - pydantic.Field(alias="Idempotency-Key"), - FieldMetadata(header=HeaderMetadata(style="simple", explode=False)), - ] = None - r"""A unique identifier to ensure idempotent behaviour for subsequent requests.""" - - bill_payment_prototype: Annotated[ - Optional[shared_billpaymentprototype.BillPaymentPrototype], - FieldMetadata(request=RequestMetadata(media_type="application/json")), - ] = None - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["Idempotency-Key", "billPaymentPrototype"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m +from codat_sync_for_payables.api.bill_payments import CreateBillPaymentRequest +from codat_sync_for_payables.api.bill_payments import CreateBillPaymentRequestTypedDict diff --git a/sync-for-payables/src/codat_sync_for_payables/models/operations/create_connection.py b/sync-for-payables/src/codat_sync_for_payables/models/operations/create_connection.py index 52e97da8c..3ddaafadf 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/operations/create_connection.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/operations/create_connection.py @@ -1,81 +1,6 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.models.operations.create_connection — re-export of the create_connection operation envelope.""" -from __future__ import annotations -from codat_sync_for_payables.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_payables.utils import ( - FieldMetadata, - PathParamMetadata, - RequestMetadata, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class CreateConnectionRequestBodyTypedDict(TypedDict): - platform_key: NotRequired[str] - r"""A unique 4-letter key to represent a platform in each integration. View [accounting](https://docs.codat.io/integrations/accounting/overview#platform-keys), [banking](https://docs.codat.io/integrations/banking/overview#platform-keys), and [commerce](https://docs.codat.io/integrations/commerce/overview#platform-keys) platform keys.""" - - -class CreateConnectionRequestBody(BaseModel): - platform_key: Annotated[Optional[str], pydantic.Field(alias="platformKey")] = None - r"""A unique 4-letter key to represent a platform in each integration. View [accounting](https://docs.codat.io/integrations/accounting/overview#platform-keys), [banking](https://docs.codat.io/integrations/banking/overview#platform-keys), and [commerce](https://docs.codat.io/integrations/commerce/overview#platform-keys) platform keys.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["platformKey"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m - - -class CreateConnectionRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - request_body: NotRequired[CreateConnectionRequestBodyTypedDict] - - -class CreateConnectionRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - request_body: Annotated[ - Optional[CreateConnectionRequestBody], - FieldMetadata(request=RequestMetadata(media_type="application/json")), - ] = None - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["RequestBody"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m - - -try: - CreateConnectionRequestBody.model_rebuild() -except NameError: - pass +from codat_sync_for_payables.api.connections import CreateConnectionRequest +from codat_sync_for_payables.models.create_connection_request import CreateConnectionRequest as CreateConnectionRequestBody +from codat_sync_for_payables.models.create_connection_request import CreateConnectionRequestTypedDict as CreateConnectionRequestBodyTypedDict +from codat_sync_for_payables.api.connections import CreateConnectionRequestTypedDict diff --git a/sync-for-payables/src/codat_sync_for_payables/models/operations/create_supplier.py b/sync-for-payables/src/codat_sync_for_payables/models/operations/create_supplier.py index 22ec11b27..00ef9816d 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/operations/create_supplier.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/operations/create_supplier.py @@ -1,71 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.models.operations.create_supplier — re-export of the create_supplier operation envelope.""" -from __future__ import annotations -from codat_sync_for_payables.models.shared import ( - supplierprototype as shared_supplierprototype, -) -from codat_sync_for_payables.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_payables.utils import ( - FieldMetadata, - HeaderMetadata, - PathParamMetadata, - RequestMetadata, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class CreateSupplierRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - connection_id: str - r"""Unique identifier for a connection.""" - idempotency_key: NotRequired[str] - r"""A unique identifier to ensure idempotent behaviour for subsequent requests.""" - supplier_prototype: NotRequired[shared_supplierprototype.SupplierPrototypeTypedDict] - - -class CreateSupplierRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - connection_id: Annotated[ - str, - pydantic.Field(alias="connectionId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a connection.""" - - idempotency_key: Annotated[ - Optional[str], - pydantic.Field(alias="Idempotency-Key"), - FieldMetadata(header=HeaderMetadata(style="simple", explode=False)), - ] = None - r"""A unique identifier to ensure idempotent behaviour for subsequent requests.""" - - supplier_prototype: Annotated[ - Optional[shared_supplierprototype.SupplierPrototype], - FieldMetadata(request=RequestMetadata(media_type="application/json")), - ] = None - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["Idempotency-Key", "supplierPrototype"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m +from codat_sync_for_payables.api.suppliers import CreateSupplierRequest +from codat_sync_for_payables.api.suppliers import CreateSupplierRequestTypedDict diff --git a/sync-for-payables/src/codat_sync_for_payables/models/operations/delete_company.py b/sync-for-payables/src/codat_sync_for_payables/models/operations/delete_company.py index efb24dca6..a7e6cba94 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/operations/delete_company.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/operations/delete_company.py @@ -1,21 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.models.operations.delete_company — re-export of the delete_company operation envelope.""" -from __future__ import annotations -from codat_sync_for_payables.types import BaseModel -from codat_sync_for_payables.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class DeleteCompanyRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - - -class DeleteCompanyRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" +from codat_sync_for_payables.api.companies import DeleteCompanyRequest +from codat_sync_for_payables.api.companies import DeleteCompanyRequestTypedDict diff --git a/sync-for-payables/src/codat_sync_for_payables/models/operations/delete_connection.py b/sync-for-payables/src/codat_sync_for_payables/models/operations/delete_connection.py index cdaa556cd..c496362c6 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/operations/delete_connection.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/operations/delete_connection.py @@ -1,30 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.models.operations.delete_connection — re-export of the delete_connection operation envelope.""" -from __future__ import annotations -from codat_sync_for_payables.types import BaseModel -from codat_sync_for_payables.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class DeleteConnectionRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - connection_id: str - r"""Unique identifier for a connection.""" - - -class DeleteConnectionRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - connection_id: Annotated[ - str, - pydantic.Field(alias="connectionId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a connection.""" +from codat_sync_for_payables.api.connections import DeleteConnectionRequest +from codat_sync_for_payables.api.connections import DeleteConnectionRequestTypedDict diff --git a/sync-for-payables/src/codat_sync_for_payables/models/operations/download_bill_attachment.py b/sync-for-payables/src/codat_sync_for_payables/models/operations/download_bill_attachment.py index c22442f7c..75de587be 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/operations/download_bill_attachment.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/operations/download_bill_attachment.py @@ -1,48 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.models.operations.download_bill_attachment — re-export of the download_bill_attachment operation envelope.""" -from __future__ import annotations -from codat_sync_for_payables.types import BaseModel -from codat_sync_for_payables.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class DownloadBillAttachmentRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - connection_id: str - r"""Unique identifier for a connection.""" - bill_id: str - r"""Unique identifier for a bill.""" - attachment_id: str - r"""Unique identifier for an attachment.""" - - -class DownloadBillAttachmentRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - connection_id: Annotated[ - str, - pydantic.Field(alias="connectionId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a connection.""" - - bill_id: Annotated[ - str, - pydantic.Field(alias="billId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a bill.""" - - attachment_id: Annotated[ - str, - pydantic.Field(alias="attachmentId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for an attachment.""" +from codat_sync_for_payables.api.bills import DownloadBillAttachmentRequest +from codat_sync_for_payables.api.bills import DownloadBillAttachmentRequestTypedDict diff --git a/sync-for-payables/src/codat_sync_for_payables/models/operations/get_company.py b/sync-for-payables/src/codat_sync_for_payables/models/operations/get_company.py index 67ba39ebb..6b5d8af72 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/operations/get_company.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/operations/get_company.py @@ -1,21 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.models.operations.get_company — re-export of the get_company operation envelope.""" -from __future__ import annotations -from codat_sync_for_payables.types import BaseModel -from codat_sync_for_payables.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class GetCompanyRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - - -class GetCompanyRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" +from codat_sync_for_payables.api.companies import GetCompanyRequest +from codat_sync_for_payables.api.companies import GetCompanyRequestTypedDict diff --git a/sync-for-payables/src/codat_sync_for_payables/models/operations/get_company_information.py b/sync-for-payables/src/codat_sync_for_payables/models/operations/get_company_information.py index 6844e6789..085ea705e 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/operations/get_company_information.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/operations/get_company_information.py @@ -1,30 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.models.operations.get_company_information — re-export of the get_company_information operation envelope.""" -from __future__ import annotations -from codat_sync_for_payables.types import BaseModel -from codat_sync_for_payables.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class GetCompanyInformationRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - connection_id: str - r"""Unique identifier for a connection.""" - - -class GetCompanyInformationRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - connection_id: Annotated[ - str, - pydantic.Field(alias="connectionId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a connection.""" +from codat_sync_for_payables.api.company_information import GetCompanyInformationRequest +from codat_sync_for_payables.api.company_information import GetCompanyInformationRequestTypedDict diff --git a/sync-for-payables/src/codat_sync_for_payables/models/operations/get_connection.py b/sync-for-payables/src/codat_sync_for_payables/models/operations/get_connection.py index 3dee0e6e1..f413ede00 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/operations/get_connection.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/operations/get_connection.py @@ -1,30 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.models.operations.get_connection — re-export of the get_connection operation envelope.""" -from __future__ import annotations -from codat_sync_for_payables.types import BaseModel -from codat_sync_for_payables.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class GetConnectionRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - connection_id: str - r"""Unique identifier for a connection.""" - - -class GetConnectionRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - connection_id: Annotated[ - str, - pydantic.Field(alias="connectionId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a connection.""" +from codat_sync_for_payables.api.connections import GetConnectionRequest +from codat_sync_for_payables.api.connections import GetConnectionRequestTypedDict diff --git a/sync-for-payables/src/codat_sync_for_payables/models/operations/get_mapping_options_bills.py b/sync-for-payables/src/codat_sync_for_payables/models/operations/get_mapping_options_bills.py index da8cae88e..29cab31ca 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/operations/get_mapping_options_bills.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/operations/get_mapping_options_bills.py @@ -1,70 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.models.operations.get_mapping_options_bills — re-export of the get_mapping_options_bills operation envelope.""" -from __future__ import annotations -from codat_sync_for_payables.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_payables.utils import ( - FieldMetadata, - PathParamMetadata, - QueryParamMetadata, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class GetMappingOptionsBillsRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - connection_id: str - r"""Unique identifier for a connection.""" - continuation_token: NotRequired[str] - r"""Retrieve the next page of results using the continuation token from the previous response.""" - status_query: NotRequired[str] - r"""Codat query string allows you to filter by `status` (`status=Active||status=Archived`). [Learn more](https://docs.codat.io/using-the-api/querying) about Codat's query string.""" - - -class GetMappingOptionsBillsRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - connection_id: Annotated[ - str, - pydantic.Field(alias="connectionId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a connection.""" - - continuation_token: Annotated[ - Optional[str], - pydantic.Field(alias="continuationToken"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = None - r"""Retrieve the next page of results using the continuation token from the previous response.""" - - status_query: Annotated[ - Optional[str], - pydantic.Field(alias="statusQuery"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = None - r"""Codat query string allows you to filter by `status` (`status=Active||status=Archived`). [Learn more](https://docs.codat.io/using-the-api/querying) about Codat's query string.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["continuationToken", "statusQuery"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m +from codat_sync_for_payables.api.bills import GetMappingOptionsBillsRequest +from codat_sync_for_payables.api.bills import GetMappingOptionsBillsRequestTypedDict diff --git a/sync-for-payables/src/codat_sync_for_payables/models/operations/get_mapping_options_payments.py b/sync-for-payables/src/codat_sync_for_payables/models/operations/get_mapping_options_payments.py index dded63b8a..909d6adbf 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/operations/get_mapping_options_payments.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/operations/get_mapping_options_payments.py @@ -1,70 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.models.operations.get_mapping_options_payments — re-export of the get_mapping_options_payments operation envelope.""" -from __future__ import annotations -from codat_sync_for_payables.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_payables.utils import ( - FieldMetadata, - PathParamMetadata, - QueryParamMetadata, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class GetMappingOptionsPaymentsRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - connection_id: str - r"""Unique identifier for a connection.""" - continuation_token: NotRequired[str] - r"""Retrieve the next page of results using the continuation token from the previous response.""" - status_query: NotRequired[str] - r"""Codat query string allows you to filter by `status` (`status=Active||status=Archived`). [Learn more](https://docs.codat.io/using-the-api/querying) about Codat's query string.""" - - -class GetMappingOptionsPaymentsRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - connection_id: Annotated[ - str, - pydantic.Field(alias="connectionId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a connection.""" - - continuation_token: Annotated[ - Optional[str], - pydantic.Field(alias="continuationToken"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = None - r"""Retrieve the next page of results using the continuation token from the previous response.""" - - status_query: Annotated[ - Optional[str], - pydantic.Field(alias="statusQuery"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = None - r"""Codat query string allows you to filter by `status` (`status=Active||status=Archived`). [Learn more](https://docs.codat.io/using-the-api/querying) about Codat's query string.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["continuationToken", "statusQuery"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m +from codat_sync_for_payables.api.bill_payments import GetMappingOptionsPaymentsRequest +from codat_sync_for_payables.api.bill_payments import GetMappingOptionsPaymentsRequestTypedDict diff --git a/sync-for-payables/src/codat_sync_for_payables/models/operations/list_bill_attachments.py b/sync-for-payables/src/codat_sync_for_payables/models/operations/list_bill_attachments.py index 077e7104a..eba6cab44 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/operations/list_bill_attachments.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/operations/list_bill_attachments.py @@ -1,39 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.models.operations.list_bill_attachments — re-export of the list_bill_attachments operation envelope.""" -from __future__ import annotations -from codat_sync_for_payables.types import BaseModel -from codat_sync_for_payables.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class ListBillAttachmentsRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - connection_id: str - r"""Unique identifier for a connection.""" - bill_id: str - r"""Unique identifier for a bill.""" - - -class ListBillAttachmentsRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - connection_id: Annotated[ - str, - pydantic.Field(alias="connectionId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a connection.""" - - bill_id: Annotated[ - str, - pydantic.Field(alias="billId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a bill.""" +from codat_sync_for_payables.api.bills import ListBillAttachmentsRequest +from codat_sync_for_payables.api.bills import ListBillAttachmentsRequestTypedDict diff --git a/sync-for-payables/src/codat_sync_for_payables/models/operations/list_bills.py b/sync-for-payables/src/codat_sync_for_payables/models/operations/list_bills.py index 0f224f151..6d24b54dd 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/operations/list_bills.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/operations/list_bills.py @@ -1,69 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.models.operations.list_bills — re-export of the list_bills operation envelope.""" -from __future__ import annotations -from codat_sync_for_payables.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_payables.utils import ( - FieldMetadata, - PathParamMetadata, - QueryParamMetadata, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class ListBillsRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - connection_id: str - r"""Unique identifier for a connection.""" - continuation_token: NotRequired[str] - r"""Retrieve the next page of results using the continuation token from the previous response.""" - query: NotRequired[str] - r"""Codat query string allows you to filter by `status` and `sourceModifiedDate`. Learn more about Codat's query string [here](https://docs.codat.io/using-the-api/querying). Platfrom specfic statuses: Xero supports Open | PartiallyPaid | Paid | Void | Draft. Qbo supports Open | PartiallyPaid | Paid. FreeAgent supports Open | PartiallyPaid | Paid.""" - - -class ListBillsRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - connection_id: Annotated[ - str, - pydantic.Field(alias="connectionId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a connection.""" - - continuation_token: Annotated[ - Optional[str], - pydantic.Field(alias="continuationToken"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = None - r"""Retrieve the next page of results using the continuation token from the previous response.""" - - query: Annotated[ - Optional[str], - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = None - r"""Codat query string allows you to filter by `status` and `sourceModifiedDate`. Learn more about Codat's query string [here](https://docs.codat.io/using-the-api/querying). Platfrom specfic statuses: Xero supports Open | PartiallyPaid | Paid | Void | Draft. Qbo supports Open | PartiallyPaid | Paid. FreeAgent supports Open | PartiallyPaid | Paid.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["continuationToken", "query"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m +from codat_sync_for_payables.api.bills import ListBillsRequest +from codat_sync_for_payables.api.bills import ListBillsRequestTypedDict diff --git a/sync-for-payables/src/codat_sync_for_payables/models/operations/list_companies.py b/sync-for-payables/src/codat_sync_for_payables/models/operations/list_companies.py index 7d919e1b5..93d24f779 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/operations/list_companies.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/operations/list_companies.py @@ -1,72 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.models.operations.list_companies — re-export of the list_companies operation envelope.""" -from __future__ import annotations -from codat_sync_for_payables.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_payables.utils import FieldMetadata, QueryParamMetadata -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class ListCompaniesRequestTypedDict(TypedDict): - page: NotRequired[int] - r"""Page number. [Read more](https://docs.codat.io/using-the-api/paging).""" - page_size: NotRequired[int] - r"""Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging).""" - query: NotRequired[str] - r"""Codat query string. [Read more](https://docs.codat.io/using-the-api/querying).""" - order_by: NotRequired[str] - r"""Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).""" - tags: NotRequired[str] - r"""Filter companies by tags using the \"equals\" (=), \"not equals\" (!=), and \"contains\" (~) operators with [Codat’s query language](https://docs.codat.io/using-the-api/querying).""" - - -class ListCompaniesRequest(BaseModel): - page: Annotated[ - Optional[int], - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = 1 - r"""Page number. [Read more](https://docs.codat.io/using-the-api/paging).""" - - page_size: Annotated[ - Optional[int], - pydantic.Field(alias="pageSize"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = 100 - r"""Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging).""" - - query: Annotated[ - Optional[str], - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = None - r"""Codat query string. [Read more](https://docs.codat.io/using-the-api/querying).""" - - order_by: Annotated[ - Optional[str], - pydantic.Field(alias="orderBy"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = None - r"""Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).""" - - tags: Annotated[ - Optional[str], - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = None - r"""Filter companies by tags using the \"equals\" (=), \"not equals\" (!=), and \"contains\" (~) operators with [Codat’s query language](https://docs.codat.io/using-the-api/querying).""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["page", "pageSize", "query", "orderBy", "tags"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m +from codat_sync_for_payables.api.companies import ListCompaniesRequest +from codat_sync_for_payables.api.companies import ListCompaniesRequestTypedDict diff --git a/sync-for-payables/src/codat_sync_for_payables/models/operations/list_connections.py b/sync-for-payables/src/codat_sync_for_payables/models/operations/list_connections.py index 0a3e5b2c3..d32992071 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/operations/list_connections.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/operations/list_connections.py @@ -1,77 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.models.operations.list_connections — re-export of the list_connections operation envelope.""" -from __future__ import annotations -from codat_sync_for_payables.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_payables.utils import ( - FieldMetadata, - PathParamMetadata, - QueryParamMetadata, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class ListConnectionsRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - page: NotRequired[int] - r"""Page number. [Read more](https://docs.codat.io/using-the-api/paging).""" - page_size: NotRequired[int] - r"""Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging).""" - query: NotRequired[str] - r"""Codat query string. [Read more](https://docs.codat.io/using-the-api/querying).""" - order_by: NotRequired[str] - r"""Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).""" - - -class ListConnectionsRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - page: Annotated[ - Optional[int], - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = 1 - r"""Page number. [Read more](https://docs.codat.io/using-the-api/paging).""" - - page_size: Annotated[ - Optional[int], - pydantic.Field(alias="pageSize"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = 100 - r"""Number of records to return in a page. [Read more](https://docs.codat.io/using-the-api/paging).""" - - query: Annotated[ - Optional[str], - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = None - r"""Codat query string. [Read more](https://docs.codat.io/using-the-api/querying).""" - - order_by: Annotated[ - Optional[str], - pydantic.Field(alias="orderBy"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = None - r"""Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["page", "pageSize", "query", "orderBy"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m +from codat_sync_for_payables.api.connections import ListConnectionsRequest +from codat_sync_for_payables.api.connections import ListConnectionsRequestTypedDict diff --git a/sync-for-payables/src/codat_sync_for_payables/models/operations/list_suppliers.py b/sync-for-payables/src/codat_sync_for_payables/models/operations/list_suppliers.py index 499b422d5..a435bbd02 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/operations/list_suppliers.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/operations/list_suppliers.py @@ -1,69 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.models.operations.list_suppliers — re-export of the list_suppliers operation envelope.""" -from __future__ import annotations -from codat_sync_for_payables.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_payables.utils import ( - FieldMetadata, - PathParamMetadata, - QueryParamMetadata, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class ListSuppliersRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - connection_id: str - r"""Unique identifier for a connection.""" - continuation_token: NotRequired[str] - r"""Retrieve the next page of results using the continuation token from the previous response.""" - query: NotRequired[str] - r"""Codat query string allows you to filter by `sourceModifiedDate` or if a supplier is `Active` or `Archived` in the accounting software. Learn more about Codat's query string [here](https://docs.codat.io/using-the-api/querying).""" - - -class ListSuppliersRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - connection_id: Annotated[ - str, - pydantic.Field(alias="connectionId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a connection.""" - - continuation_token: Annotated[ - Optional[str], - pydantic.Field(alias="continuationToken"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = None - r"""Retrieve the next page of results using the continuation token from the previous response.""" - - query: Annotated[ - Optional[str], - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = None - r"""Codat query string allows you to filter by `sourceModifiedDate` or if a supplier is `Active` or `Archived` in the accounting software. Learn more about Codat's query string [here](https://docs.codat.io/using-the-api/querying).""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["continuationToken", "query"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m +from codat_sync_for_payables.api.suppliers import ListSuppliersRequest +from codat_sync_for_payables.api.suppliers import ListSuppliersRequestTypedDict diff --git a/sync-for-payables/src/codat_sync_for_payables/models/operations/replace_company.py b/sync-for-payables/src/codat_sync_for_payables/models/operations/replace_company.py index 1670273e5..174a6b4ae 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/operations/replace_company.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/operations/replace_company.py @@ -1,54 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.models.operations.replace_company — re-export of the replace_company operation envelope.""" -from __future__ import annotations -from codat_sync_for_payables.models.shared import ( - companyrequestbody as shared_companyrequestbody, -) -from codat_sync_for_payables.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_payables.utils import ( - FieldMetadata, - PathParamMetadata, - RequestMetadata, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class ReplaceCompanyRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - company_request_body: NotRequired[ - shared_companyrequestbody.CompanyRequestBodyTypedDict - ] - - -class ReplaceCompanyRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - company_request_body: Annotated[ - Optional[shared_companyrequestbody.CompanyRequestBody], - FieldMetadata(request=RequestMetadata(media_type="application/json")), - ] = None - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["CompanyRequestBody"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m +from codat_sync_for_payables.api.companies import ReplaceCompanyRequest +from codat_sync_for_payables.api.companies import ReplaceCompanyRequestTypedDict diff --git a/sync-for-payables/src/codat_sync_for_payables/models/operations/unlink_connection.py b/sync-for-payables/src/codat_sync_for_payables/models/operations/unlink_connection.py index 507c063f7..4e3ce2c9c 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/operations/unlink_connection.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/operations/unlink_connection.py @@ -1,87 +1,6 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.models.operations.unlink_connection — re-export of the unlink_connection operation envelope.""" -from __future__ import annotations -from codat_sync_for_payables.models.shared import ( - dataconnectionstatus as shared_dataconnectionstatus, -) -from codat_sync_for_payables.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_payables.utils import ( - FieldMetadata, - PathParamMetadata, - RequestMetadata, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class UnlinkConnectionUpdateConnectionTypedDict(TypedDict): - status: NotRequired[shared_dataconnectionstatus.DataConnectionStatus] - r"""The current authorization status of the data connection.""" - - -class UnlinkConnectionUpdateConnection(BaseModel): - status: Optional[shared_dataconnectionstatus.DataConnectionStatus] = None - r"""The current authorization status of the data connection.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["status"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m - - -class UnlinkConnectionRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - connection_id: str - r"""Unique identifier for a connection.""" - request_body: NotRequired[UnlinkConnectionUpdateConnectionTypedDict] - - -class UnlinkConnectionRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - connection_id: Annotated[ - str, - pydantic.Field(alias="connectionId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a connection.""" - - request_body: Annotated[ - Optional[UnlinkConnectionUpdateConnection], - FieldMetadata(request=RequestMetadata(media_type="application/json")), - ] = None - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["RequestBody"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m +from codat_sync_for_payables.api.connections import UnlinkConnectionRequest +from codat_sync_for_payables.api.connections import UnlinkConnectionRequestTypedDict +from codat_sync_for_payables.models.update_connection import UpdateConnection as UnlinkConnectionUpdateConnection +from codat_sync_for_payables.models.update_connection import UpdateConnectionTypedDict as UnlinkConnectionUpdateConnectionTypedDict diff --git a/sync-for-payables/src/codat_sync_for_payables/models/operations/update_bill.py b/sync-for-payables/src/codat_sync_for_payables/models/operations/update_bill.py index d92fc24bb..0dbe9446e 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/operations/update_bill.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/operations/update_bill.py @@ -1,78 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.models.operations.update_bill — re-export of the update_bill operation envelope.""" -from __future__ import annotations -from codat_sync_for_payables.models.shared import billprototype as shared_billprototype -from codat_sync_for_payables.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_payables.utils import ( - FieldMetadata, - HeaderMetadata, - PathParamMetadata, - RequestMetadata, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class UpdateBillRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - connection_id: str - r"""Unique identifier for a connection.""" - bill_id: str - r"""Unique identifier for a bill.""" - idempotency_key: NotRequired[str] - r"""A unique identifier to ensure idempotent behaviour for subsequent requests.""" - bill_prototype: NotRequired[shared_billprototype.BillPrototypeTypedDict] - - -class UpdateBillRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - connection_id: Annotated[ - str, - pydantic.Field(alias="connectionId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a connection.""" - - bill_id: Annotated[ - str, - pydantic.Field(alias="billId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a bill.""" - - idempotency_key: Annotated[ - Optional[str], - pydantic.Field(alias="Idempotency-Key"), - FieldMetadata(header=HeaderMetadata(style="simple", explode=False)), - ] = None - r"""A unique identifier to ensure idempotent behaviour for subsequent requests.""" - - bill_prototype: Annotated[ - Optional[shared_billprototype.BillPrototype], - FieldMetadata(request=RequestMetadata(media_type="application/json")), - ] = None - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["Idempotency-Key", "billPrototype"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m +from codat_sync_for_payables.api.bills import UpdateBillRequest +from codat_sync_for_payables.api.bills import UpdateBillRequestTypedDict diff --git a/sync-for-payables/src/codat_sync_for_payables/models/operations/update_company.py b/sync-for-payables/src/codat_sync_for_payables/models/operations/update_company.py index 5d3abdc41..575b16c71 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/operations/update_company.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/operations/update_company.py @@ -1,54 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.models.operations.update_company — re-export of the update_company operation envelope.""" -from __future__ import annotations -from codat_sync_for_payables.models.shared import ( - companyupdaterequest as shared_companyupdaterequest, -) -from codat_sync_for_payables.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_payables.utils import ( - FieldMetadata, - PathParamMetadata, - RequestMetadata, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class UpdateCompanyRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - company_update_request: NotRequired[ - shared_companyupdaterequest.CompanyUpdateRequestTypedDict - ] - - -class UpdateCompanyRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - company_update_request: Annotated[ - Optional[shared_companyupdaterequest.CompanyUpdateRequest], - FieldMetadata(request=RequestMetadata(media_type="application/json")), - ] = None - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["CompanyUpdateRequest"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m +from codat_sync_for_payables.api.companies import UpdateCompanyRequest +from codat_sync_for_payables.api.companies import UpdateCompanyRequestTypedDict diff --git a/sync-for-payables/src/codat_sync_for_payables/models/operations/update_supplier.py b/sync-for-payables/src/codat_sync_for_payables/models/operations/update_supplier.py index 6ea647c5b..9c44bd8ec 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/operations/update_supplier.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/operations/update_supplier.py @@ -1,70 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.models.operations.update_supplier — re-export of the update_supplier operation envelope.""" -from __future__ import annotations -from codat_sync_for_payables.models.shared import ( - supplierprototype as shared_supplierprototype, -) -from codat_sync_for_payables.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_payables.utils import ( - FieldMetadata, - PathParamMetadata, - RequestMetadata, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class UpdateSupplierRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - connection_id: str - r"""Unique identifier for a connection.""" - supplier_id: str - r"""Unique identifier for a supplier.""" - supplier_prototype: NotRequired[shared_supplierprototype.SupplierPrototypeTypedDict] - - -class UpdateSupplierRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - connection_id: Annotated[ - str, - pydantic.Field(alias="connectionId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a connection.""" - - supplier_id: Annotated[ - str, - pydantic.Field(alias="supplierId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a supplier.""" - - supplier_prototype: Annotated[ - Optional[shared_supplierprototype.SupplierPrototype], - FieldMetadata(request=RequestMetadata(media_type="application/json")), - ] = None - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["supplierPrototype"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m +from codat_sync_for_payables.api.suppliers import UpdateSupplierRequest +from codat_sync_for_payables.api.suppliers import UpdateSupplierRequestTypedDict diff --git a/sync-for-payables/src/codat_sync_for_payables/models/operations/upload_bill_attachment.py b/sync-for-payables/src/codat_sync_for_payables/models/operations/upload_bill_attachment.py index 2fe0d0c7e..413235a5b 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/operations/upload_bill_attachment.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/operations/upload_bill_attachment.py @@ -1,70 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.models.operations.upload_bill_attachment — re-export of the upload_bill_attachment operation envelope.""" -from __future__ import annotations -from codat_sync_for_payables.models.shared import ( - attachmentupload as shared_attachmentupload, -) -from codat_sync_for_payables.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_payables.utils import ( - FieldMetadata, - PathParamMetadata, - RequestMetadata, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class UploadBillAttachmentRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - connection_id: str - r"""Unique identifier for a connection.""" - bill_id: str - r"""Unique identifier for a bill.""" - attachment_upload: NotRequired[shared_attachmentupload.AttachmentUploadTypedDict] - - -class UploadBillAttachmentRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - connection_id: Annotated[ - str, - pydantic.Field(alias="connectionId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a connection.""" - - bill_id: Annotated[ - str, - pydantic.Field(alias="billId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a bill.""" - - attachment_upload: Annotated[ - Optional[shared_attachmentupload.AttachmentUpload], - FieldMetadata(request=RequestMetadata(media_type="multipart/form-data")), - ] = None - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["AttachmentUpload"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m +from codat_sync_for_payables.api.bills import UploadBillAttachmentRequest +from codat_sync_for_payables.api.bills import UploadBillAttachmentRequestTypedDict diff --git a/sync-for-payables/src/codat_sync_for_payables/models/paging_info.py b/sync-for-payables/src/codat_sync_for_payables/models/paging_info.py new file mode 100644 index 000000000..00f3f3b3d --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/models/paging_info.py @@ -0,0 +1,113 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List +from typing_extensions import Annotated, NotRequired, TypedDict +from codat_sync_for_payables.models.shared.links import Links, LinksTypedDict +from typing import Optional, Set +from typing_extensions import Self + +class PagingInfo(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + PagingInfo + """ # noqa: E501 + page_number: int = Field(description="Current page number.", alias="pageNumber") + page_size: int = Field(description="Number of items to return in results array.", alias="pageSize") + total_results: int = Field(description="Total number of items.", alias="totalResults") + links: Links = Field(alias="_links") + __properties: ClassVar[List[str]] = ["pageNumber", "pageSize", "totalResults", "_links"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of PagingInfo from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of links + if self.links: + _dict['_links'] = self.links.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of PagingInfo from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "pageNumber": obj.get("pageNumber"), + "pageSize": obj.get("pageSize"), + "totalResults": obj.get("totalResults"), + "_links": Links.from_dict(obj["_links"]) if obj.get("_links") is not None else None + }) + return _obj + + + + + +class PagingInfoTypedDict(TypedDict): + """TypedDict variant of PagingInfo, for dict-literal request/response inputs.""" + page_number: NotRequired[int] + page_size: NotRequired[int] + total_results: NotRequired[int] + links: NotRequired[LinksTypedDict] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/pull_operation.py b/sync-for-payables/src/codat_sync_for_payables/models/pull_operation.py new file mode 100644 index 000000000..248228935 --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/models/pull_operation.py @@ -0,0 +1,140 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +from codat_sync_for_payables.models.dataset_status import DatasetStatus +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class PullOperation(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + Information about a queued, in progress or completed pull operation. *Formally called `dataset`* + """ # noqa: E501 + id: str = Field(description="Unique identifier of the pull operation.") + company_id: str = Field(description="Unique identifier of the company associated to this pull operation.", alias="companyId") + connection_id: str = Field(description="Unique identifier of the connection associated to this pull operation.", alias="connectionId") + data_type: str = Field(description="The data type you are requesting in a pull operation.", alias="dataType") + status: str = Field(description="The current status of the dataset.") + status_description: Optional[str] = Field(default=None, description="Additional information about the dataset status.", alias="statusDescription") + error_message: Optional[str] = Field(default=None, description="A message about a transient or persistent error returned by Codat or the source platform.", alias="errorMessage") + requested: str = Field(description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.") + completed: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.") + progress: int = Field(description="An integer signifying the progress of the pull operation.") + is_completed: bool = Field(description="`True` if the pull operation is completed successfully. The `isCompleted` property is not queryable. To filter failed pull operations, query by `status!=Complete&&status!=NotSupported` instead.", alias="isCompleted") + is_errored: bool = Field(description="`True` if the pull operation entered an error state.", alias="isErrored") + __properties: ClassVar[List[str]] = ["id", "companyId", "connectionId", "dataType", "status", "statusDescription", "errorMessage", "requested", "completed", "progress", "isCompleted", "isErrored"] + + @field_validator('status') + def status_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['Initial', 'Queued', 'Fetching', 'MapQueued', 'Mapping', 'Complete', 'FetchError', 'MapError', 'InternalError', 'ProcessingQueued', 'Processing', 'ProcessingError', 'ValidationQueued', 'Validating', 'ValidationError', 'AuthError', 'Cancelled', 'NotSupported', 'RateLimitError', 'PermissionsError', 'PrerequisiteNotMet']): + raise ValueError("must be one of enum values ('Initial', 'Queued', 'Fetching', 'MapQueued', 'Mapping', 'Complete', 'FetchError', 'MapError', 'InternalError', 'ProcessingQueued', 'Processing', 'ProcessingError', 'ValidationQueued', 'Validating', 'ValidationError', 'AuthError', 'Cancelled', 'NotSupported', 'RateLimitError', 'PermissionsError', 'PrerequisiteNotMet')") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of PullOperation from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of PullOperation from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "companyId": obj.get("companyId"), + "connectionId": obj.get("connectionId"), + "dataType": obj.get("dataType"), + "status": obj.get("status"), + "statusDescription": obj.get("statusDescription"), + "errorMessage": obj.get("errorMessage"), + "requested": obj.get("requested"), + "completed": obj.get("completed"), + "progress": obj.get("progress"), + "isCompleted": obj.get("isCompleted"), + "isErrored": obj.get("isErrored") + }) + return _obj + + + + + +class PullOperationTypedDict(TypedDict): + """TypedDict variant of PullOperation, for dict-literal request/response inputs.""" + id: NotRequired[str] + company_id: NotRequired[str] + connection_id: NotRequired[str] + data_type: NotRequired[str] + status: NotRequired[str] + status_description: NotRequired[Optional[str]] + error_message: NotRequired[Optional[str]] + requested: NotRequired[str] + completed: NotRequired[Optional[str]] + progress: NotRequired[int] + is_completed: NotRequired[bool] + is_errored: NotRequired[bool] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/pull_operations.py b/sync-for-payables/src/codat_sync_for_payables/models/pull_operations.py new file mode 100644 index 000000000..736fb6f19 --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/models/pull_operations.py @@ -0,0 +1,124 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated, NotRequired, TypedDict +from codat_sync_for_payables.models.shared.links import Links, LinksTypedDict +from codat_sync_for_payables.models.pull_operation import PullOperation, PullOperationTypedDict +from typing import Optional, Set +from typing_extensions import Self + +class PullOperations(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + PullOperations + """ # noqa: E501 + page_number: int = Field(description="Current page number.", alias="pageNumber") + page_size: int = Field(description="Number of items to return in results array.", alias="pageSize") + total_results: int = Field(description="Total number of items.", alias="totalResults") + links: Links = Field(alias="_links") + results: Optional[List[PullOperation]] = None + __properties: ClassVar[List[str]] = ["pageNumber", "pageSize", "totalResults", "_links", "results"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of PullOperations from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of links + if self.links: + _dict['_links'] = self.links.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in results (list) + _items = [] + if self.results: + for _item_results in self.results: + if _item_results: + _items.append(_item_results.to_dict()) + _dict['results'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of PullOperations from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "pageNumber": obj.get("pageNumber"), + "pageSize": obj.get("pageSize"), + "totalResults": obj.get("totalResults"), + "_links": Links.from_dict(obj["_links"]) if obj.get("_links") is not None else None, + "results": [PullOperation.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None + }) + return _obj + + + + + +class PullOperationsTypedDict(TypedDict): + """TypedDict variant of PullOperations, for dict-literal request/response inputs.""" + page_number: NotRequired[int] + page_size: NotRequired[int] + total_results: NotRequired[int] + links: NotRequired[LinksTypedDict] + results: NotRequired[Optional[List[PullOperationTypedDict]]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/push_change_type.py b/sync-for-payables/src/codat_sync_for_payables/models/push_change_type.py new file mode 100644 index 000000000..b60c9e40a --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/models/push_change_type.py @@ -0,0 +1,40 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class PushChangeType(str, Enum): + """ + Type of change being applied to record in third party platform. + """ + + """ + allowed enum values + """ + UNKNOWN = 'Unknown' + CREATED = 'Created' + MODIFIED = 'Modified' + DELETED = 'Deleted' + ATTACHMENT_UPLOADED = 'AttachmentUploaded' + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of PushChangeType from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sync-for-payables/src/codat_sync_for_payables/models/push_operation.py b/sync-for-payables/src/codat_sync_for_payables/models/push_operation.py new file mode 100644 index 000000000..9ba653b9e --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/models/push_operation.py @@ -0,0 +1,159 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +from codat_sync_for_payables.models.data_type import DataType +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_sync_for_payables.models.push_operation_change import PushOperationChange, PushOperationChangeTypedDict +from codat_sync_for_payables.models.push_operation_status import PushOperationStatus +from codat_sync_for_payables.models.validation import Validation, ValidationTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class PushOperation(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + PushOperation + """ # noqa: E501 + changes: Optional[List[PushOperationChange]] = Field(default=None, description="Contains a single entry that communicates which record has changed and the manner in which it changed. ") + data_type: Optional[str] = Field(default=None, description="Available data types", alias="dataType") + company_id: str = Field(description="Unique identifier for your SMB in Codat.", alias="companyId") + push_operation_key: str = Field(description="A unique identifier generated by Codat to represent this single push operation. This identifier can be used to track the status of the push, and should be persisted.", alias="pushOperationKey") + data_connection_key: str = Field(description="Unique identifier for a company's data connection.", alias="dataConnectionKey") + requested_on_utc: str = Field(description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.", alias="requestedOnUtc") + completed_on_utc: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.", alias="completedOnUtc") + timeout_in_minutes: Optional[int] = Field(default=None, description="Number of minutes the push operation must complete within before it times out.", alias="timeoutInMinutes") + timeout_in_seconds: Optional[int] = Field(default=None, description="Number of seconds the push operation must complete within before it times out.", alias="timeoutInSeconds") + status: PushOperationStatus + error_message: Optional[str] = Field(default=None, description="A message about the error.", alias="errorMessage") + validation: Optional[Validation] = None + status_code: int = Field(description="Push status code.", alias="statusCode") + __properties: ClassVar[List[str]] = ["changes", "dataType", "companyId", "pushOperationKey", "dataConnectionKey", "requestedOnUtc", "completedOnUtc", "timeoutInMinutes", "timeoutInSeconds", "status", "errorMessage", "validation", "statusCode"] + + @field_validator('data_type') + def data_type_validate_enum(cls, value): + """Validates the enum""" + if value is None: + return value + + if value not in set(['accountTransactions', 'balanceSheet', 'bankAccounts', 'bankTransactions', 'billCreditNotes', 'billPayments', 'bills', 'cashFlowStatement', 'chartOfAccounts', 'company', 'creditNotes', 'customers', 'directCosts', 'directIncomes', 'invoices', 'itemReceipts', 'items', 'journalEntries', 'journals', 'paymentMethods', 'payments', 'profitAndLoss', 'purchaseOrders', 'salesOrders', 'suppliers', 'taxRates', 'trackingCategories', 'transfers', 'banking-accountBalances', 'banking-accounts', 'banking-transactionCategories', 'banking-transactions', 'commerce-companyInfo', 'commerce-customers', 'commerce-disputes', 'commerce-locations', 'commerce-orders', 'commerce-paymentMethods', 'commerce-payments', 'commerce-productCategories', 'commerce-products', 'commerce-taxComponents', 'commerce-transactions']): + raise ValueError("must be one of enum values ('accountTransactions', 'balanceSheet', 'bankAccounts', 'bankTransactions', 'billCreditNotes', 'billPayments', 'bills', 'cashFlowStatement', 'chartOfAccounts', 'company', 'creditNotes', 'customers', 'directCosts', 'directIncomes', 'invoices', 'itemReceipts', 'items', 'journalEntries', 'journals', 'paymentMethods', 'payments', 'profitAndLoss', 'purchaseOrders', 'salesOrders', 'suppliers', 'taxRates', 'trackingCategories', 'transfers', 'banking-accountBalances', 'banking-accounts', 'banking-transactionCategories', 'banking-transactions', 'commerce-companyInfo', 'commerce-customers', 'commerce-disputes', 'commerce-locations', 'commerce-orders', 'commerce-paymentMethods', 'commerce-payments', 'commerce-productCategories', 'commerce-products', 'commerce-taxComponents', 'commerce-transactions')") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of PushOperation from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in changes (list) + _items = [] + if self.changes: + for _item_changes in self.changes: + if _item_changes: + _items.append(_item_changes.to_dict()) + _dict['changes'] = _items + # override the default output from pydantic by calling `to_dict()` of validation + if self.validation: + _dict['validation'] = self.validation.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of PushOperation from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "changes": [PushOperationChange.from_dict(_item) for _item in obj["changes"]] if obj.get("changes") is not None else None, + "dataType": obj.get("dataType"), + "companyId": obj.get("companyId"), + "pushOperationKey": obj.get("pushOperationKey"), + "dataConnectionKey": obj.get("dataConnectionKey"), + "requestedOnUtc": obj.get("requestedOnUtc"), + "completedOnUtc": obj.get("completedOnUtc"), + "timeoutInMinutes": obj.get("timeoutInMinutes"), + "timeoutInSeconds": obj.get("timeoutInSeconds"), + "status": obj.get("status"), + "errorMessage": obj.get("errorMessage"), + "validation": Validation.from_dict(obj["validation"]) if obj.get("validation") is not None else None, + "statusCode": obj.get("statusCode") + }) + return _obj + + + + + +class PushOperationTypedDict(TypedDict): + """TypedDict variant of PushOperation, for dict-literal request/response inputs.""" + changes: NotRequired[Optional[List[PushOperationChangeTypedDict]]] + data_type: NotRequired[Optional[str]] + company_id: NotRequired[str] + push_operation_key: NotRequired[str] + data_connection_key: NotRequired[str] + requested_on_utc: NotRequired[str] + completed_on_utc: NotRequired[Optional[str]] + timeout_in_minutes: NotRequired[Optional[int]] + timeout_in_seconds: NotRequired[Optional[int]] + status: PushOperationStatus + error_message: NotRequired[Optional[str]] + validation: NotRequired[Optional[ValidationTypedDict]] + status_code: NotRequired[int] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/push_operation_change.py b/sync-for-payables/src/codat_sync_for_payables/models/push_operation_change.py new file mode 100644 index 000000000..2b02b7fad --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/models/push_operation_change.py @@ -0,0 +1,110 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_sync_for_payables.models.push_change_type import PushChangeType +from codat_sync_for_payables.models.push_operation_ref import PushOperationRef, PushOperationRefTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class PushOperationChange(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + PushOperationChange + """ # noqa: E501 + type: Optional[PushChangeType] = None + record_ref: Optional[PushOperationRef] = Field(default=None, alias="recordRef") + attachment_id: Optional[str] = Field(default=None, description="Unique identifier for the attachment created otherwise null.", alias="attachmentId") + __properties: ClassVar[List[str]] = ["type", "recordRef", "attachmentId"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of PushOperationChange from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of record_ref + if self.record_ref: + _dict['recordRef'] = self.record_ref.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of PushOperationChange from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "type": obj.get("type"), + "recordRef": PushOperationRef.from_dict(obj["recordRef"]) if obj.get("recordRef") is not None else None, + "attachmentId": obj.get("attachmentId") + }) + return _obj + + + + + +class PushOperationChangeTypedDict(TypedDict): + """TypedDict variant of PushOperationChange, for dict-literal request/response inputs.""" + type: NotRequired[Optional[PushChangeType]] + record_ref: NotRequired[Optional[PushOperationRefTypedDict]] + attachment_id: NotRequired[Optional[str]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/push_operation_ref.py b/sync-for-payables/src/codat_sync_for_payables/models/push_operation_ref.py new file mode 100644 index 000000000..07ad81c79 --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/models/push_operation_ref.py @@ -0,0 +1,127 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +from codat_sync_for_payables.models.data_type import DataType +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class PushOperationRef(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + PushOperationRef + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Unique identifier for a push operation.") + data_type: Optional[str] = Field(default=None, description="Available data types", alias="dataType") + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["id", "dataType"] + + @field_validator('data_type') + def data_type_validate_enum(cls, value): + """Validates the enum""" + if value is None: + return value + + if value not in set(['accountTransactions', 'balanceSheet', 'bankAccounts', 'bankTransactions', 'billCreditNotes', 'billPayments', 'bills', 'cashFlowStatement', 'chartOfAccounts', 'company', 'creditNotes', 'customers', 'directCosts', 'directIncomes', 'invoices', 'itemReceipts', 'items', 'journalEntries', 'journals', 'paymentMethods', 'payments', 'profitAndLoss', 'purchaseOrders', 'salesOrders', 'suppliers', 'taxRates', 'trackingCategories', 'transfers', 'banking-accountBalances', 'banking-accounts', 'banking-transactionCategories', 'banking-transactions', 'commerce-companyInfo', 'commerce-customers', 'commerce-disputes', 'commerce-locations', 'commerce-orders', 'commerce-paymentMethods', 'commerce-payments', 'commerce-productCategories', 'commerce-products', 'commerce-taxComponents', 'commerce-transactions']): + raise ValueError("must be one of enum values ('accountTransactions', 'balanceSheet', 'bankAccounts', 'bankTransactions', 'billCreditNotes', 'billPayments', 'bills', 'cashFlowStatement', 'chartOfAccounts', 'company', 'creditNotes', 'customers', 'directCosts', 'directIncomes', 'invoices', 'itemReceipts', 'items', 'journalEntries', 'journals', 'paymentMethods', 'payments', 'profitAndLoss', 'purchaseOrders', 'salesOrders', 'suppliers', 'taxRates', 'trackingCategories', 'transfers', 'banking-accountBalances', 'banking-accounts', 'banking-transactionCategories', 'banking-transactions', 'commerce-companyInfo', 'commerce-customers', 'commerce-disputes', 'commerce-locations', 'commerce-orders', 'commerce-paymentMethods', 'commerce-payments', 'commerce-productCategories', 'commerce-products', 'commerce-taxComponents', 'commerce-transactions')") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of PushOperationRef from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + * Fields in `self.additional_properties` are added to the output dict. + """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of PushOperationRef from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "dataType": obj.get("dataType") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + + + + +class PushOperationRefTypedDict(TypedDict): + """TypedDict variant of PushOperationRef, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + data_type: NotRequired[Optional[str]] + additional_properties: NotRequired[Dict[str, Any]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/push_operation_status.py b/sync-for-payables/src/codat_sync_for_payables/models/push_operation_status.py new file mode 100644 index 000000000..a82945668 --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/models/push_operation_status.py @@ -0,0 +1,39 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class PushOperationStatus(str, Enum): + """ + The current status of the push operation. + """ + + """ + allowed enum values + """ + PENDING = 'Pending' + FAILED = 'Failed' + SUCCESS = 'Success' + TIMED_OUT = 'TimedOut' + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of PushOperationStatus from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sync-for-payables/src/codat_sync_for_payables/models/push_operations.py b/sync-for-payables/src/codat_sync_for_payables/models/push_operations.py new file mode 100644 index 000000000..2ba962db4 --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/models/push_operations.py @@ -0,0 +1,124 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated, NotRequired, TypedDict +from codat_sync_for_payables.models.shared.links import Links, LinksTypedDict +from codat_sync_for_payables.models.push_operation import PushOperation, PushOperationTypedDict +from typing import Optional, Set +from typing_extensions import Self + +class PushOperations(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + PushOperations + """ # noqa: E501 + page_number: int = Field(description="Current page number.", alias="pageNumber") + page_size: int = Field(description="Number of items to return in results array.", alias="pageSize") + total_results: int = Field(description="Total number of items.", alias="totalResults") + links: Links = Field(alias="_links") + results: Optional[List[PushOperation]] = None + __properties: ClassVar[List[str]] = ["pageNumber", "pageSize", "totalResults", "_links", "results"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of PushOperations from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of links + if self.links: + _dict['_links'] = self.links.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in results (list) + _items = [] + if self.results: + for _item_results in self.results: + if _item_results: + _items.append(_item_results.to_dict()) + _dict['results'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of PushOperations from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "pageNumber": obj.get("pageNumber"), + "pageSize": obj.get("pageSize"), + "totalResults": obj.get("totalResults"), + "_links": Links.from_dict(obj["_links"]) if obj.get("_links") is not None else None, + "results": [PushOperation.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None + }) + return _obj + + + + + +class PushOperationsTypedDict(TypedDict): + """TypedDict variant of PushOperations, for dict-literal request/response inputs.""" + page_number: NotRequired[int] + page_size: NotRequired[int] + total_results: NotRequired[int] + links: NotRequired[LinksTypedDict] + results: NotRequired[Optional[List[PushOperationTypedDict]]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/__init__.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/__init__.py index 9f391cc6d..374c52d20 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/__init__.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/__init__.py @@ -1,290 +1,293 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.models.shared — domain-shared models.""" -from typing import Any, TYPE_CHECKING - -from codat_sync_for_payables.utils.dynamic_imports import lazy_getattr, lazy_dir +from importlib import import_module +from typing import TYPE_CHECKING if TYPE_CHECKING: - from .accountmappingoption import ( - AccountMappingOption, - AccountMappingOptionTypedDict, - ) - from .accountstatus import AccountStatus - from .address import Address, AddressTypedDict - from .addresstype import AddressType - from .attachment import Attachment, AttachmentTypedDict - from .attachmentupload import AttachmentUpload, AttachmentUploadTypedDict - from .bankaccount import BankAccount, BankAccountTypedDict - from .bankaccountmappingoption import ( - BankAccountMappingOption, - BankAccountMappingOptionTypedDict, - ) - from .bankaccountprototype import ( - BankAccountPrototype, - BankAccountPrototypeTypedDict, - ) - from .bankaccountstatus import BankAccountStatus - from .bankaccounttype import BankAccountType - from .bill import Bill, BillTypedDict - from .billaccountref import BillAccountRef, BillAccountRefTypedDict - from .billlineitem import BillLineItem, BillLineItemTypedDict - from .billmappingoptions import BillMappingOptions, BillMappingOptionsTypedDict - from .billpayment import BillPayment, BillPaymentTypedDict - from .billpaymentaccountref import ( - BillPaymentAccountRef, - BillPaymentAccountRefTypedDict, - ) - from .billpaymentprototype import ( - BillPaymentPrototype, - BillPaymentPrototypeTypedDict, - ) - from .billprototype import BillPrototype, BillPrototypeTypedDict - from .bills import Bills, BillsTypedDict - from .billstatus import BillStatus - from .billtaxrateref import BillTaxRateRef, BillTaxRateRefTypedDict - from .codatfile import CodatFile, CodatFileTypedDict - from .companies import Companies, CompaniesTypedDict - from .company import Company, CompanyTypedDict - from .companyinformation import CompanyInformation, CompanyInformationTypedDict - from .companyreference import ( - CompanyReference, - CompanyReferenceLinks, - CompanyReferenceLinksTypedDict, - CompanyReferenceTypedDict, - ) - from .companyrequestbody import CompanyRequestBody, CompanyRequestBodyTypedDict - from .companyupdaterequest import ( - CompanyUpdateRequest, - CompanyUpdateRequestTypedDict, - ) - from .connection import Connection, ConnectionTypedDict, SourceType - from .connections import Connections, ConnectionsTypedDict - from .dataconnectionerror import ( - DataConnectionError, - DataConnectionErrorTypedDict, - ErrorStatus, - ) - from .dataconnectionstatus import DataConnectionStatus - from .errorvalidation import ErrorValidation, ErrorValidationTypedDict - from .errorvalidationitem import ErrorValidationItem, ErrorValidationItemTypedDict - from .halref import HalRef, HalRefTypedDict - from .links import Links, LinksTypedDict - from .pagination import Pagination, PaginationTypedDict - from .paymentmappingoptions import ( - PaymentMappingOptions, - PaymentMappingOptionsTypedDict, - ) from .security import Security, SecurityTypedDict - from .supplier import Supplier, SupplierTypedDict - from .supplierprototype import SupplierPrototype, SupplierPrototypeTypedDict - from .supplierref import SupplierRef, SupplierRefTypedDict - from .suppliers import Suppliers, SuppliersTypedDict - from .supplierstatus import SupplierStatus - from .taxratemappingoption import ( - TaxRateMappingOption, - TaxRateMappingOptionTypedDict, - TaxRateStatus, - ) - from .trackingref import DataType, TrackingRef, TrackingRefTypedDict - -__all__ = [ - "AccountMappingOption", - "AccountMappingOptionTypedDict", - "AccountStatus", - "Address", - "AddressType", - "AddressTypedDict", - "Attachment", - "AttachmentTypedDict", - "AttachmentUpload", - "AttachmentUploadTypedDict", - "BankAccount", - "BankAccountMappingOption", - "BankAccountMappingOptionTypedDict", - "BankAccountPrototype", - "BankAccountPrototypeTypedDict", - "BankAccountStatus", - "BankAccountType", - "BankAccountTypedDict", - "Bill", - "BillAccountRef", - "BillAccountRefTypedDict", - "BillLineItem", - "BillLineItemTypedDict", - "BillMappingOptions", - "BillMappingOptionsTypedDict", - "BillPayment", - "BillPaymentAccountRef", - "BillPaymentAccountRefTypedDict", - "BillPaymentPrototype", - "BillPaymentPrototypeTypedDict", - "BillPaymentTypedDict", - "BillPrototype", - "BillPrototypeTypedDict", - "BillStatus", - "BillTaxRateRef", - "BillTaxRateRefTypedDict", - "BillTypedDict", - "Bills", - "BillsTypedDict", - "CodatFile", - "CodatFileTypedDict", - "Companies", - "CompaniesTypedDict", - "Company", - "CompanyInformation", - "CompanyInformationTypedDict", - "CompanyReference", - "CompanyReferenceLinks", - "CompanyReferenceLinksTypedDict", - "CompanyReferenceTypedDict", - "CompanyRequestBody", - "CompanyRequestBodyTypedDict", - "CompanyTypedDict", - "CompanyUpdateRequest", - "CompanyUpdateRequestTypedDict", - "Connection", - "ConnectionTypedDict", - "Connections", - "ConnectionsTypedDict", - "DataConnectionError", - "DataConnectionErrorTypedDict", - "DataConnectionStatus", - "DataType", - "ErrorStatus", - "ErrorValidation", - "ErrorValidationItem", - "ErrorValidationItemTypedDict", - "ErrorValidationTypedDict", - "HalRef", - "HalRefTypedDict", - "Links", - "LinksTypedDict", - "Pagination", - "PaginationTypedDict", - "PaymentMappingOptions", - "PaymentMappingOptionsTypedDict", - "Security", - "SecurityTypedDict", - "SourceType", - "Supplier", - "SupplierPrototype", - "SupplierPrototypeTypedDict", - "SupplierRef", - "SupplierRefTypedDict", - "SupplierStatus", - "SupplierTypedDict", - "Suppliers", - "SuppliersTypedDict", - "TaxRateMappingOption", - "TaxRateMappingOptionTypedDict", - "TaxRateStatus", - "TrackingRef", - "TrackingRefTypedDict", -] + from codat_sync_for_payables.models.shared.accountmappingoption import AccountMappingOption, AccountMappingOptionTypedDict + from codat_sync_for_payables.models.shared.accountstatus import AccountStatus + from codat_sync_for_payables.models.shared.address import Address, AddressTypedDict + from codat_sync_for_payables.models.shared.addresstype import AddressType + from codat_sync_for_payables.models.shared.attachment import Attachment, AttachmentTypedDict + from codat_sync_for_payables.models.shared.bankaccount import BankAccount, BankAccountTypedDict + from codat_sync_for_payables.models.shared.bankaccountmappingoption import BankAccountMappingOption, BankAccountMappingOptionTypedDict + from codat_sync_for_payables.models.shared.bankaccountprototype import BankAccountPrototype, BankAccountPrototypeTypedDict + from codat_sync_for_payables.models.shared.bankaccountstatus import BankAccountStatus + from codat_sync_for_payables.models.shared.bankaccounttype import BankAccountType + from codat_sync_for_payables.models.shared.bill import Bill, BillTypedDict + from codat_sync_for_payables.models.shared.billaccountref import BillAccountRef, BillAccountRefTypedDict + from codat_sync_for_payables.models.bill_data_type import BillDataType + from codat_sync_for_payables.models.bill_event_payload import BillEventPayload, BillEventPayloadTypedDict + from codat_sync_for_payables.models.bill_event_webhook import BillEventWebhook, BillEventWebhookTypedDict + from codat_sync_for_payables.models.shared.billlineitem import BillLineItem, BillLineItemTypedDict + from codat_sync_for_payables.models.shared.billmappingoptions import BillMappingOptions, BillMappingOptionsTypedDict + from codat_sync_for_payables.models.shared.billpayment import BillPayment, BillPaymentTypedDict + from codat_sync_for_payables.models.shared.billpaymentaccountref import BillPaymentAccountRef, BillPaymentAccountRefTypedDict + from codat_sync_for_payables.models.shared.billpaymentprototype import BillPaymentPrototype, BillPaymentPrototypeTypedDict + from codat_sync_for_payables.models.shared.billprototype import BillPrototype, BillPrototypeTypedDict + from codat_sync_for_payables.models.shared.billstatus import BillStatus + from codat_sync_for_payables.models.shared.billtaxrateref import BillTaxRateRef, BillTaxRateRefTypedDict + from codat_sync_for_payables.models.shared.bills import Bills, BillsTypedDict + from codat_sync_for_payables.models.shared.clientratelimitwebhook import ClientRateLimitWebhook, ClientRateLimitWebhookTypedDict + from codat_sync_for_payables.models.shared.clientratelimitwebhookpayload import ClientRateLimitWebhookPayload, ClientRateLimitWebhookPayloadTypedDict + from codat_sync_for_payables.models.shared.companies import Companies, CompaniesTypedDict + from codat_sync_for_payables.models.shared.company import Company, CompanyTypedDict + from codat_sync_for_payables.models.company_details import CompanyDetails, CompanyDetailsTypedDict + from codat_sync_for_payables.models.shared.companyinformation import CompanyInformation, CompanyInformationTypedDict + from codat_sync_for_payables.models.shared.companyreference import CompanyReference, CompanyReferenceTypedDict + from codat_sync_for_payables.models.company_reference_links import CompanyReferenceLinks, CompanyReferenceLinksTypedDict + from codat_sync_for_payables.models.shared.companyrequestbody import CompanyRequestBody, CompanyRequestBodyTypedDict + from codat_sync_for_payables.models.shared.companyupdaterequest import CompanyUpdateRequest, CompanyUpdateRequestTypedDict + from codat_sync_for_payables.models.shared.connection import Connection, ConnectionTypedDict + from codat_sync_for_payables.models.shared.connections import Connections, ConnectionsTypedDict + from codat_sync_for_payables.models.create_connection_request import CreateConnectionRequest, CreateConnectionRequestTypedDict + from codat_sync_for_payables.models.current_status import CurrentStatus + from codat_sync_for_payables.models.shared.dataconnectionerror import DataConnectionError, DataConnectionErrorTypedDict + from codat_sync_for_payables.models.shared.dataconnectionstatus import DataConnectionStatus + from codat_sync_for_payables.models.data_status import DataStatus, DataStatusTypedDict + from codat_sync_for_payables.models.data_type import DataType + from codat_sync_for_payables.models.data_types import DataTypes + from codat_sync_for_payables.models.dataset_status import DatasetStatus + from codat_sync_for_payables.models.error_message import ErrorMessage, ErrorMessageTypedDict + from codat_sync_for_payables.models.error_status import ErrorStatus + from codat_sync_for_payables.models.shared.errorvalidation import ErrorValidation, ErrorValidationTypedDict + from codat_sync_for_payables.models.shared.errorvalidationitem import ErrorValidationItem, ErrorValidationItemTypedDict + from codat_sync_for_payables.models.shared.halref import HalRef, HalRefTypedDict + from codat_sync_for_payables.models.shared.links import Links, LinksTypedDict + from codat_sync_for_payables.models.shared.pagination import Pagination, PaginationTypedDict + from codat_sync_for_payables.models.paging_info import PagingInfo, PagingInfoTypedDict + from codat_sync_for_payables.models.shared.paymentmappingoptions import PaymentMappingOptions, PaymentMappingOptionsTypedDict + from codat_sync_for_payables.models.pull_operation import PullOperation, PullOperationTypedDict + from codat_sync_for_payables.models.pull_operations import PullOperations, PullOperationsTypedDict + from codat_sync_for_payables.models.push_change_type import PushChangeType + from codat_sync_for_payables.models.push_operation import PushOperation, PushOperationTypedDict + from codat_sync_for_payables.models.push_operation_change import PushOperationChange, PushOperationChangeTypedDict + from codat_sync_for_payables.models.push_operation_ref import PushOperationRef, PushOperationRefTypedDict + from codat_sync_for_payables.models.push_operation_status import PushOperationStatus + from codat_sync_for_payables.models.push_operations import PushOperations, PushOperationsTypedDict + from codat_sync_for_payables.models.source_modified_date import SourceModifiedDate, SourceModifiedDateTypedDict + from codat_sync_for_payables.models.source_type import SourceType + from codat_sync_for_payables.models.status import Status + from codat_sync_for_payables.models.shared.supplier import Supplier, SupplierTypedDict + from codat_sync_for_payables.models.shared.supplierprototype import SupplierPrototype, SupplierPrototypeTypedDict + from codat_sync_for_payables.models.shared.supplierref import SupplierRef, SupplierRefTypedDict + from codat_sync_for_payables.models.shared.supplierstatus import SupplierStatus + from codat_sync_for_payables.models.shared.suppliers import Suppliers, SuppliersTypedDict + from codat_sync_for_payables.models.shared.taxratemappingoption import TaxRateMappingOption, TaxRateMappingOptionTypedDict + from codat_sync_for_payables.models.tax_rate_status import TaxRateStatus + from codat_sync_for_payables.models.shared.trackingref import TrackingRef, TrackingRefTypedDict + from codat_sync_for_payables.models.update_connection import UpdateConnection, UpdateConnectionTypedDict + from codat_sync_for_payables.models.validation import Validation, ValidationTypedDict + from codat_sync_for_payables.models.validation_item import ValidationItem, ValidationItemTypedDict + from codat_sync_for_payables.models.shared.accountmappingoption import AccountMappingOptionTypedDict as AccountMappingOptionTypedDict + from codat_sync_for_payables.models.shared.accountstatus import AccountStatus as AccountStatus + from codat_sync_for_payables.models.shared.addresstype import AddressType as AddressType + from codat_sync_for_payables.models.shared.address import AddressTypedDict as AddressTypedDict + from codat_sync_for_payables.models.shared.attachment import AttachmentTypedDict as AttachmentTypedDict + from codat_sync_for_payables.models.shared.bankaccountmappingoption import BankAccountMappingOptionTypedDict as BankAccountMappingOptionTypedDict + from codat_sync_for_payables.models.shared.bankaccountprototype import BankAccountPrototypeTypedDict as BankAccountPrototypeTypedDict + from codat_sync_for_payables.models.shared.bankaccountstatus import BankAccountStatus as BankAccountStatus + from codat_sync_for_payables.models.shared.bankaccounttype import BankAccountType as BankAccountType + from codat_sync_for_payables.models.shared.bankaccount import BankAccountTypedDict as BankAccountTypedDict + from codat_sync_for_payables.models.shared.billaccountref import BillAccountRefTypedDict as BillAccountRefTypedDict + from codat_sync_for_payables.models.shared.billlineitem import BillLineItemTypedDict as BillLineItemTypedDict + from codat_sync_for_payables.models.shared.billmappingoptions import BillMappingOptionsTypedDict as BillMappingOptionsTypedDict + from codat_sync_for_payables.models.shared.billpaymentaccountref import BillPaymentAccountRefTypedDict as BillPaymentAccountRefTypedDict + from codat_sync_for_payables.models.shared.billpaymentprototype import BillPaymentPrototypeTypedDict as BillPaymentPrototypeTypedDict + from codat_sync_for_payables.models.shared.billpayment import BillPaymentTypedDict as BillPaymentTypedDict + from codat_sync_for_payables.models.shared.billprototype import BillPrototypeTypedDict as BillPrototypeTypedDict + from codat_sync_for_payables.models.shared.billstatus import BillStatus as BillStatus + from codat_sync_for_payables.models.shared.billtaxrateref import BillTaxRateRefTypedDict as BillTaxRateRefTypedDict + from codat_sync_for_payables.models.shared.bill import BillTypedDict as BillTypedDict + from codat_sync_for_payables.models.shared.bills import BillsTypedDict as BillsTypedDict + from codat_sync_for_payables.models.shared.clientratelimitwebhookpayload import ClientRateLimitWebhookPayloadTypedDict as ClientRateLimitWebhookPayloadTypedDict + from codat_sync_for_payables.models.shared.clientratelimitwebhook import ClientRateLimitWebhookTypedDict as ClientRateLimitWebhookTypedDict + from codat_sync_for_payables.models.shared.companies import CompaniesTypedDict as CompaniesTypedDict + from codat_sync_for_payables.models.shared.companyinformation import CompanyInformationTypedDict as CompanyInformationTypedDict + from codat_sync_for_payables.models.company_reference_links import CompanyReferenceLinksTypedDict as CompanyReferenceLinksTypedDict + from codat_sync_for_payables.models.shared.companyreference import CompanyReferenceTypedDict as CompanyReferenceTypedDict + from codat_sync_for_payables.models.shared.companyrequestbody import CompanyRequestBodyTypedDict as CompanyRequestBodyTypedDict + from codat_sync_for_payables.models.shared.company import CompanyTypedDict as CompanyTypedDict + from codat_sync_for_payables.models.shared.companyupdaterequest import CompanyUpdateRequestTypedDict as CompanyUpdateRequestTypedDict + from codat_sync_for_payables.models.shared.connection import ConnectionTypedDict as ConnectionTypedDict + from codat_sync_for_payables.models.shared.connections import ConnectionsTypedDict as ConnectionsTypedDict + from codat_sync_for_payables.models.shared.dataconnectionerror import DataConnectionErrorTypedDict as DataConnectionErrorTypedDict + from codat_sync_for_payables.models.shared.dataconnectionstatus import DataConnectionStatus as DataConnectionStatus + from codat_sync_for_payables.models.data_type import DataType as DataType + from codat_sync_for_payables.models.error_status import ErrorStatus as ErrorStatus + from codat_sync_for_payables.models.shared.errorvalidationitem import ErrorValidationItemTypedDict as ErrorValidationItemTypedDict + from codat_sync_for_payables.models.shared.errorvalidation import ErrorValidationTypedDict as ErrorValidationTypedDict + from codat_sync_for_payables.models.shared.halref import HalRefTypedDict as HalRefTypedDict + from codat_sync_for_payables.models.shared.links import LinksTypedDict as LinksTypedDict + from codat_sync_for_payables.models.shared.pagination import PaginationTypedDict as PaginationTypedDict + from codat_sync_for_payables.models.shared.paymentmappingoptions import PaymentMappingOptionsTypedDict as PaymentMappingOptionsTypedDict + from codat_sync_for_payables.models.shared.security import Security as Security + from codat_sync_for_payables.models.shared.security import SecurityTypedDict as SecurityTypedDict + from codat_sync_for_payables.models.source_type import SourceType as SourceType + from codat_sync_for_payables.models.shared.supplierprototype import SupplierPrototypeTypedDict as SupplierPrototypeTypedDict + from codat_sync_for_payables.models.shared.supplierref import SupplierRefTypedDict as SupplierRefTypedDict + from codat_sync_for_payables.models.shared.supplierstatus import SupplierStatus as SupplierStatus + from codat_sync_for_payables.models.shared.supplier import SupplierTypedDict as SupplierTypedDict + from codat_sync_for_payables.models.shared.suppliers import SuppliersTypedDict as SuppliersTypedDict + from codat_sync_for_payables.models.shared.taxratemappingoption import TaxRateMappingOptionTypedDict as TaxRateMappingOptionTypedDict + from codat_sync_for_payables.models.tax_rate_status import TaxRateStatus as TaxRateStatus + from codat_sync_for_payables.models.shared.trackingref import TrackingRefTypedDict as TrackingRefTypedDict + from codat_sync_for_payables.models.shared.codatfile import CodatFile, CodatFileTypedDict + from codat_sync_for_payables.models.shared.attachmentupload import AttachmentUpload, AttachmentUploadTypedDict -_dynamic_imports: dict[str, str] = { - "AccountMappingOption": ".accountmappingoption", - "AccountMappingOptionTypedDict": ".accountmappingoption", - "AccountStatus": ".accountstatus", - "Address": ".address", - "AddressTypedDict": ".address", - "AddressType": ".addresstype", - "Attachment": ".attachment", - "AttachmentTypedDict": ".attachment", - "AttachmentUpload": ".attachmentupload", - "AttachmentUploadTypedDict": ".attachmentupload", - "BankAccount": ".bankaccount", - "BankAccountTypedDict": ".bankaccount", - "BankAccountMappingOption": ".bankaccountmappingoption", - "BankAccountMappingOptionTypedDict": ".bankaccountmappingoption", - "BankAccountPrototype": ".bankaccountprototype", - "BankAccountPrototypeTypedDict": ".bankaccountprototype", - "BankAccountStatus": ".bankaccountstatus", - "BankAccountType": ".bankaccounttype", - "Bill": ".bill", - "BillTypedDict": ".bill", - "BillAccountRef": ".billaccountref", - "BillAccountRefTypedDict": ".billaccountref", - "BillLineItem": ".billlineitem", - "BillLineItemTypedDict": ".billlineitem", - "BillMappingOptions": ".billmappingoptions", - "BillMappingOptionsTypedDict": ".billmappingoptions", - "BillPayment": ".billpayment", - "BillPaymentTypedDict": ".billpayment", - "BillPaymentAccountRef": ".billpaymentaccountref", - "BillPaymentAccountRefTypedDict": ".billpaymentaccountref", - "BillPaymentPrototype": ".billpaymentprototype", - "BillPaymentPrototypeTypedDict": ".billpaymentprototype", - "BillPrototype": ".billprototype", - "BillPrototypeTypedDict": ".billprototype", - "Bills": ".bills", - "BillsTypedDict": ".bills", - "BillStatus": ".billstatus", - "BillTaxRateRef": ".billtaxrateref", - "BillTaxRateRefTypedDict": ".billtaxrateref", - "CodatFile": ".codatfile", - "CodatFileTypedDict": ".codatfile", - "Companies": ".companies", - "CompaniesTypedDict": ".companies", - "Company": ".company", - "CompanyTypedDict": ".company", - "CompanyInformation": ".companyinformation", - "CompanyInformationTypedDict": ".companyinformation", - "CompanyReference": ".companyreference", - "CompanyReferenceLinks": ".companyreference", - "CompanyReferenceLinksTypedDict": ".companyreference", - "CompanyReferenceTypedDict": ".companyreference", - "CompanyRequestBody": ".companyrequestbody", - "CompanyRequestBodyTypedDict": ".companyrequestbody", - "CompanyUpdateRequest": ".companyupdaterequest", - "CompanyUpdateRequestTypedDict": ".companyupdaterequest", - "Connection": ".connection", - "ConnectionTypedDict": ".connection", - "SourceType": ".connection", - "Connections": ".connections", - "ConnectionsTypedDict": ".connections", - "DataConnectionError": ".dataconnectionerror", - "DataConnectionErrorTypedDict": ".dataconnectionerror", - "ErrorStatus": ".dataconnectionerror", - "DataConnectionStatus": ".dataconnectionstatus", - "ErrorValidation": ".errorvalidation", - "ErrorValidationTypedDict": ".errorvalidation", - "ErrorValidationItem": ".errorvalidationitem", - "ErrorValidationItemTypedDict": ".errorvalidationitem", - "HalRef": ".halref", - "HalRefTypedDict": ".halref", - "Links": ".links", - "LinksTypedDict": ".links", - "Pagination": ".pagination", - "PaginationTypedDict": ".pagination", - "PaymentMappingOptions": ".paymentmappingoptions", - "PaymentMappingOptionsTypedDict": ".paymentmappingoptions", - "Security": ".security", - "SecurityTypedDict": ".security", - "Supplier": ".supplier", - "SupplierTypedDict": ".supplier", - "SupplierPrototype": ".supplierprototype", - "SupplierPrototypeTypedDict": ".supplierprototype", - "SupplierRef": ".supplierref", - "SupplierRefTypedDict": ".supplierref", - "Suppliers": ".suppliers", - "SuppliersTypedDict": ".suppliers", - "SupplierStatus": ".supplierstatus", - "TaxRateMappingOption": ".taxratemappingoption", - "TaxRateMappingOptionTypedDict": ".taxratemappingoption", - "TaxRateStatus": ".taxratemappingoption", - "DataType": ".trackingref", - "TrackingRef": ".trackingref", - "TrackingRefTypedDict": ".trackingref", +_dynamic_imports: dict[str, tuple[str, str]] = { + 'AccountMappingOption': ('codat_sync_for_payables.models.shared.accountmappingoption', 'AccountMappingOption'), + 'AccountMappingOptionTypedDict': ('codat_sync_for_payables.models.shared.accountmappingoption', 'AccountMappingOptionTypedDict'), + 'AccountStatus': ('codat_sync_for_payables.models.shared.accountstatus', 'AccountStatus'), + 'Address': ('codat_sync_for_payables.models.shared.address', 'Address'), + 'AddressType': ('codat_sync_for_payables.models.shared.addresstype', 'AddressType'), + 'AddressTypedDict': ('codat_sync_for_payables.models.shared.address', 'AddressTypedDict'), + 'Attachment': ('codat_sync_for_payables.models.shared.attachment', 'Attachment'), + 'AttachmentTypedDict': ('codat_sync_for_payables.models.shared.attachment', 'AttachmentTypedDict'), + 'AttachmentUpload': ('codat_sync_for_payables.models.shared.attachmentupload', 'AttachmentUpload'), + 'AttachmentUploadTypedDict': ('codat_sync_for_payables.models.shared.attachmentupload', 'AttachmentUploadTypedDict'), + 'BankAccount': ('codat_sync_for_payables.models.shared.bankaccount', 'BankAccount'), + 'BankAccountMappingOption': ('codat_sync_for_payables.models.shared.bankaccountmappingoption', 'BankAccountMappingOption'), + 'BankAccountMappingOptionTypedDict': ('codat_sync_for_payables.models.shared.bankaccountmappingoption', 'BankAccountMappingOptionTypedDict'), + 'BankAccountPrototype': ('codat_sync_for_payables.models.shared.bankaccountprototype', 'BankAccountPrototype'), + 'BankAccountPrototypeTypedDict': ('codat_sync_for_payables.models.shared.bankaccountprototype', 'BankAccountPrototypeTypedDict'), + 'BankAccountStatus': ('codat_sync_for_payables.models.shared.bankaccountstatus', 'BankAccountStatus'), + 'BankAccountType': ('codat_sync_for_payables.models.shared.bankaccounttype', 'BankAccountType'), + 'BankAccountTypedDict': ('codat_sync_for_payables.models.shared.bankaccount', 'BankAccountTypedDict'), + 'Bill': ('codat_sync_for_payables.models.shared.bill', 'Bill'), + 'BillAccountRef': ('codat_sync_for_payables.models.shared.billaccountref', 'BillAccountRef'), + 'BillAccountRefTypedDict': ('codat_sync_for_payables.models.shared.billaccountref', 'BillAccountRefTypedDict'), + 'BillDataType': ('codat_sync_for_payables.models.bill_data_type', 'BillDataType'), + 'BillEventPayload': ('codat_sync_for_payables.models.bill_event_payload', 'BillEventPayload'), + 'BillEventPayloadTypedDict': ('codat_sync_for_payables.models.bill_event_payload', 'BillEventPayloadTypedDict'), + 'BillEventWebhook': ('codat_sync_for_payables.models.bill_event_webhook', 'BillEventWebhook'), + 'BillEventWebhookTypedDict': ('codat_sync_for_payables.models.bill_event_webhook', 'BillEventWebhookTypedDict'), + 'BillLineItem': ('codat_sync_for_payables.models.shared.billlineitem', 'BillLineItem'), + 'BillLineItemTypedDict': ('codat_sync_for_payables.models.shared.billlineitem', 'BillLineItemTypedDict'), + 'BillMappingOptions': ('codat_sync_for_payables.models.shared.billmappingoptions', 'BillMappingOptions'), + 'BillMappingOptionsTypedDict': ('codat_sync_for_payables.models.shared.billmappingoptions', 'BillMappingOptionsTypedDict'), + 'BillPayment': ('codat_sync_for_payables.models.shared.billpayment', 'BillPayment'), + 'BillPaymentAccountRef': ('codat_sync_for_payables.models.shared.billpaymentaccountref', 'BillPaymentAccountRef'), + 'BillPaymentAccountRefTypedDict': ('codat_sync_for_payables.models.shared.billpaymentaccountref', 'BillPaymentAccountRefTypedDict'), + 'BillPaymentPrototype': ('codat_sync_for_payables.models.shared.billpaymentprototype', 'BillPaymentPrototype'), + 'BillPaymentPrototypeTypedDict': ('codat_sync_for_payables.models.shared.billpaymentprototype', 'BillPaymentPrototypeTypedDict'), + 'BillPaymentTypedDict': ('codat_sync_for_payables.models.shared.billpayment', 'BillPaymentTypedDict'), + 'BillPrototype': ('codat_sync_for_payables.models.shared.billprototype', 'BillPrototype'), + 'BillPrototypeTypedDict': ('codat_sync_for_payables.models.shared.billprototype', 'BillPrototypeTypedDict'), + 'BillStatus': ('codat_sync_for_payables.models.shared.billstatus', 'BillStatus'), + 'BillTaxRateRef': ('codat_sync_for_payables.models.shared.billtaxrateref', 'BillTaxRateRef'), + 'BillTaxRateRefTypedDict': ('codat_sync_for_payables.models.shared.billtaxrateref', 'BillTaxRateRefTypedDict'), + 'BillTypedDict': ('codat_sync_for_payables.models.shared.bill', 'BillTypedDict'), + 'Bills': ('codat_sync_for_payables.models.shared.bills', 'Bills'), + 'BillsTypedDict': ('codat_sync_for_payables.models.shared.bills', 'BillsTypedDict'), + 'ClientRateLimitWebhook': ('codat_sync_for_payables.models.shared.clientratelimitwebhook', 'ClientRateLimitWebhook'), + 'ClientRateLimitWebhookPayload': ('codat_sync_for_payables.models.shared.clientratelimitwebhookpayload', 'ClientRateLimitWebhookPayload'), + 'ClientRateLimitWebhookPayloadTypedDict': ('codat_sync_for_payables.models.shared.clientratelimitwebhookpayload', 'ClientRateLimitWebhookPayloadTypedDict'), + 'ClientRateLimitWebhookTypedDict': ('codat_sync_for_payables.models.shared.clientratelimitwebhook', 'ClientRateLimitWebhookTypedDict'), + 'CodatFile': ('codat_sync_for_payables.models.shared.codatfile', 'CodatFile'), + 'CodatFileTypedDict': ('codat_sync_for_payables.models.shared.codatfile', 'CodatFileTypedDict'), + 'Companies': ('codat_sync_for_payables.models.shared.companies', 'Companies'), + 'CompaniesTypedDict': ('codat_sync_for_payables.models.shared.companies', 'CompaniesTypedDict'), + 'Company': ('codat_sync_for_payables.models.shared.company', 'Company'), + 'CompanyDetails': ('codat_sync_for_payables.models.company_details', 'CompanyDetails'), + 'CompanyDetailsTypedDict': ('codat_sync_for_payables.models.company_details', 'CompanyDetailsTypedDict'), + 'CompanyInformation': ('codat_sync_for_payables.models.shared.companyinformation', 'CompanyInformation'), + 'CompanyInformationTypedDict': ('codat_sync_for_payables.models.shared.companyinformation', 'CompanyInformationTypedDict'), + 'CompanyReference': ('codat_sync_for_payables.models.shared.companyreference', 'CompanyReference'), + 'CompanyReferenceLinks': ('codat_sync_for_payables.models.company_reference_links', 'CompanyReferenceLinks'), + 'CompanyReferenceLinksTypedDict': ('codat_sync_for_payables.models.company_reference_links', 'CompanyReferenceLinksTypedDict'), + 'CompanyReferenceTypedDict': ('codat_sync_for_payables.models.shared.companyreference', 'CompanyReferenceTypedDict'), + 'CompanyRequestBody': ('codat_sync_for_payables.models.shared.companyrequestbody', 'CompanyRequestBody'), + 'CompanyRequestBodyTypedDict': ('codat_sync_for_payables.models.shared.companyrequestbody', 'CompanyRequestBodyTypedDict'), + 'CompanyTypedDict': ('codat_sync_for_payables.models.shared.company', 'CompanyTypedDict'), + 'CompanyUpdateRequest': ('codat_sync_for_payables.models.shared.companyupdaterequest', 'CompanyUpdateRequest'), + 'CompanyUpdateRequestTypedDict': ('codat_sync_for_payables.models.shared.companyupdaterequest', 'CompanyUpdateRequestTypedDict'), + 'Connection': ('codat_sync_for_payables.models.shared.connection', 'Connection'), + 'ConnectionTypedDict': ('codat_sync_for_payables.models.shared.connection', 'ConnectionTypedDict'), + 'Connections': ('codat_sync_for_payables.models.shared.connections', 'Connections'), + 'ConnectionsTypedDict': ('codat_sync_for_payables.models.shared.connections', 'ConnectionsTypedDict'), + 'CreateConnectionRequest': ('codat_sync_for_payables.models.create_connection_request', 'CreateConnectionRequest'), + 'CreateConnectionRequestTypedDict': ('codat_sync_for_payables.models.create_connection_request', 'CreateConnectionRequestTypedDict'), + 'CurrentStatus': ('codat_sync_for_payables.models.current_status', 'CurrentStatus'), + 'DataConnectionError': ('codat_sync_for_payables.models.shared.dataconnectionerror', 'DataConnectionError'), + 'DataConnectionErrorTypedDict': ('codat_sync_for_payables.models.shared.dataconnectionerror', 'DataConnectionErrorTypedDict'), + 'DataConnectionStatus': ('codat_sync_for_payables.models.shared.dataconnectionstatus', 'DataConnectionStatus'), + 'DataStatus': ('codat_sync_for_payables.models.data_status', 'DataStatus'), + 'DataStatusTypedDict': ('codat_sync_for_payables.models.data_status', 'DataStatusTypedDict'), + 'DataType': ('codat_sync_for_payables.models.data_type', 'DataType'), + 'DataTypes': ('codat_sync_for_payables.models.data_types', 'DataTypes'), + 'DatasetStatus': ('codat_sync_for_payables.models.dataset_status', 'DatasetStatus'), + 'ErrorMessage': ('codat_sync_for_payables.models.error_message', 'ErrorMessage'), + 'ErrorMessageTypedDict': ('codat_sync_for_payables.models.error_message', 'ErrorMessageTypedDict'), + 'ErrorStatus': ('codat_sync_for_payables.models.error_status', 'ErrorStatus'), + 'ErrorValidation': ('codat_sync_for_payables.models.shared.errorvalidation', 'ErrorValidation'), + 'ErrorValidationItem': ('codat_sync_for_payables.models.shared.errorvalidationitem', 'ErrorValidationItem'), + 'ErrorValidationItemTypedDict': ('codat_sync_for_payables.models.shared.errorvalidationitem', 'ErrorValidationItemTypedDict'), + 'ErrorValidationTypedDict': ('codat_sync_for_payables.models.shared.errorvalidation', 'ErrorValidationTypedDict'), + 'HalRef': ('codat_sync_for_payables.models.shared.halref', 'HalRef'), + 'HalRefTypedDict': ('codat_sync_for_payables.models.shared.halref', 'HalRefTypedDict'), + 'Links': ('codat_sync_for_payables.models.shared.links', 'Links'), + 'LinksTypedDict': ('codat_sync_for_payables.models.shared.links', 'LinksTypedDict'), + 'Pagination': ('codat_sync_for_payables.models.shared.pagination', 'Pagination'), + 'PaginationTypedDict': ('codat_sync_for_payables.models.shared.pagination', 'PaginationTypedDict'), + 'PagingInfo': ('codat_sync_for_payables.models.paging_info', 'PagingInfo'), + 'PagingInfoTypedDict': ('codat_sync_for_payables.models.paging_info', 'PagingInfoTypedDict'), + 'PaymentMappingOptions': ('codat_sync_for_payables.models.shared.paymentmappingoptions', 'PaymentMappingOptions'), + 'PaymentMappingOptionsTypedDict': ('codat_sync_for_payables.models.shared.paymentmappingoptions', 'PaymentMappingOptionsTypedDict'), + 'PullOperation': ('codat_sync_for_payables.models.pull_operation', 'PullOperation'), + 'PullOperationTypedDict': ('codat_sync_for_payables.models.pull_operation', 'PullOperationTypedDict'), + 'PullOperations': ('codat_sync_for_payables.models.pull_operations', 'PullOperations'), + 'PullOperationsTypedDict': ('codat_sync_for_payables.models.pull_operations', 'PullOperationsTypedDict'), + 'PushChangeType': ('codat_sync_for_payables.models.push_change_type', 'PushChangeType'), + 'PushOperation': ('codat_sync_for_payables.models.push_operation', 'PushOperation'), + 'PushOperationChange': ('codat_sync_for_payables.models.push_operation_change', 'PushOperationChange'), + 'PushOperationChangeTypedDict': ('codat_sync_for_payables.models.push_operation_change', 'PushOperationChangeTypedDict'), + 'PushOperationRef': ('codat_sync_for_payables.models.push_operation_ref', 'PushOperationRef'), + 'PushOperationRefTypedDict': ('codat_sync_for_payables.models.push_operation_ref', 'PushOperationRefTypedDict'), + 'PushOperationStatus': ('codat_sync_for_payables.models.push_operation_status', 'PushOperationStatus'), + 'PushOperationTypedDict': ('codat_sync_for_payables.models.push_operation', 'PushOperationTypedDict'), + 'PushOperations': ('codat_sync_for_payables.models.push_operations', 'PushOperations'), + 'PushOperationsTypedDict': ('codat_sync_for_payables.models.push_operations', 'PushOperationsTypedDict'), + 'Security': ('codat_sync_for_payables.models.shared.security', 'Security'), + 'SecurityTypedDict': ('codat_sync_for_payables.models.shared.security', 'SecurityTypedDict'), + 'SourceModifiedDate': ('codat_sync_for_payables.models.source_modified_date', 'SourceModifiedDate'), + 'SourceModifiedDateTypedDict': ('codat_sync_for_payables.models.source_modified_date', 'SourceModifiedDateTypedDict'), + 'SourceType': ('codat_sync_for_payables.models.source_type', 'SourceType'), + 'Status': ('codat_sync_for_payables.models.status', 'Status'), + 'Supplier': ('codat_sync_for_payables.models.shared.supplier', 'Supplier'), + 'SupplierPrototype': ('codat_sync_for_payables.models.shared.supplierprototype', 'SupplierPrototype'), + 'SupplierPrototypeTypedDict': ('codat_sync_for_payables.models.shared.supplierprototype', 'SupplierPrototypeTypedDict'), + 'SupplierRef': ('codat_sync_for_payables.models.shared.supplierref', 'SupplierRef'), + 'SupplierRefTypedDict': ('codat_sync_for_payables.models.shared.supplierref', 'SupplierRefTypedDict'), + 'SupplierStatus': ('codat_sync_for_payables.models.shared.supplierstatus', 'SupplierStatus'), + 'SupplierTypedDict': ('codat_sync_for_payables.models.shared.supplier', 'SupplierTypedDict'), + 'Suppliers': ('codat_sync_for_payables.models.shared.suppliers', 'Suppliers'), + 'SuppliersTypedDict': ('codat_sync_for_payables.models.shared.suppliers', 'SuppliersTypedDict'), + 'TaxRateMappingOption': ('codat_sync_for_payables.models.shared.taxratemappingoption', 'TaxRateMappingOption'), + 'TaxRateMappingOptionTypedDict': ('codat_sync_for_payables.models.shared.taxratemappingoption', 'TaxRateMappingOptionTypedDict'), + 'TaxRateStatus': ('codat_sync_for_payables.models.tax_rate_status', 'TaxRateStatus'), + 'TrackingRef': ('codat_sync_for_payables.models.shared.trackingref', 'TrackingRef'), + 'TrackingRefTypedDict': ('codat_sync_for_payables.models.shared.trackingref', 'TrackingRefTypedDict'), + 'UpdateConnection': ('codat_sync_for_payables.models.update_connection', 'UpdateConnection'), + 'UpdateConnectionTypedDict': ('codat_sync_for_payables.models.update_connection', 'UpdateConnectionTypedDict'), + 'Validation': ('codat_sync_for_payables.models.validation', 'Validation'), + 'ValidationItem': ('codat_sync_for_payables.models.validation_item', 'ValidationItem'), + 'ValidationItemTypedDict': ('codat_sync_for_payables.models.validation_item', 'ValidationItemTypedDict'), + 'ValidationTypedDict': ('codat_sync_for_payables.models.validation', 'ValidationTypedDict'), } -def __getattr__(attr_name: str) -> Any: - return lazy_getattr( - attr_name, package=__package__, dynamic_imports=_dynamic_imports - ) +def __getattr__(attr_name): + try: + module_path, source_name = _dynamic_imports[attr_name] + except KeyError: + raise AttributeError( + f"module {__name__!r} has no attribute {attr_name!r}" + ) from None + module = import_module(module_path, __package__) + return getattr(module, source_name) def __dir__(): - return lazy_dir(dynamic_imports=_dynamic_imports) + return sorted(set(globals()) | set(_dynamic_imports)) diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/accountmappingoption.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/accountmappingoption.py index 3e9371409..968bb518e 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/accountmappingoption.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/accountmappingoption.py @@ -1,112 +1,123 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .accountstatus import AccountStatus -from codat_sync_for_payables.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Bill pay (synchronous solution) + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | -class AccountMappingOptionTypedDict(TypedDict): - id: NotRequired[str] - r"""Identifier for the account, unique for the company.""" - nominal_code: NotRequired[Nullable[str]] - r"""Reference given to each nominal account for a business. It ensures money is allocated to the correct account. This code isn't a unique identifier in the Codat system.""" - name: NotRequired[Nullable[str]] - r"""Name of the account.""" - type: NotRequired[Nullable[str]] - r"""Type of account.""" - currency: NotRequired[str] - r"""The currency data type in Codat is the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code, e.g. _GBP_. - - ## Unknown currencies - - In line with the ISO 4217 specification, the code _XXX_ is used when the data source does not return a currency for a transaction. - - There are only a very small number of edge cases where this currency code is returned by the Codat system. - """ - status: NotRequired[AccountStatus] - r"""The current status of the account.""" - source_modified_date: NotRequired[str] + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class AccountMappingOption(BaseModel): - id: Optional[str] = None - r"""Identifier for the account, unique for the company.""" - nominal_code: Annotated[ - OptionalNullable[str], pydantic.Field(alias="nominalCode") - ] = UNSET - r"""Reference given to each nominal account for a business. It ensures money is allocated to the correct account. This code isn't a unique identifier in the Codat system.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - name: OptionalNullable[str] = UNSET - r"""Name of the account.""" +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_sync_for_payables.models.shared.accountstatus import AccountStatus +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict - type: OptionalNullable[str] = UNSET - r"""Type of account.""" +from codat_sync_for_payables.types import OptionalNullable, UNSET, UNSET_SENTINEL +class AccountMappingOption(BaseModel): - currency: Optional[str] = None - r"""The currency data type in Codat is the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code, e.g. _GBP_. + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'name', 'nominalCode', 'nominal_code', 'type'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + AccountMappingOption + """ # noqa: E501 + source_modified_date: Optional[str] = Field(default=None, description="The date when a record was last modified in the accounting software, usually by the business or a business process. For example, when payments are made against an invoice. It is not populated ([read more](https://docs.codat.io/using-the-api/modified-dates#source-modified-date)) when: - Pulling attachments - The accounting software does not provide modification dates for a data type - A record has been deleted from the source platform and Codat doesn't have a record of when the deletion occurred - A record has been voided. For certain platforms that soft delete records, `isDeleted` metadata is used to identify void records In Codat's data model, dates and times are represented using the ISO 8601 standard.", alias="sourceModifiedDate") + id: Optional[str] = Field(default=None, description="Identifier for the account, unique for the company.") + nominal_code: OptionalNullable[str] = Field(default=UNSET, description="Reference given to each nominal account for a business. It ensures money is allocated to the correct account. This code isn't a unique identifier in the Codat system.", alias="nominalCode") + name: OptionalNullable[str] = Field(default=UNSET, description="Name of the account.") + type: OptionalNullable[str] = Field(default=UNSET, description="Type of account.") + currency: Optional[str] = Field(default=None, description="The currency data type in Codat is the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code, e.g. _GBP_. ## Unknown currencies In line with the ISO 4217 specification, the code _XXX_ is used when the data source does not return a currency for a transaction. There are only a very small number of edge cases where this currency code is returned by the Codat system.") + status: Optional[AccountStatus] = None + __properties: ClassVar[List[str]] = ["sourceModifiedDate", "id", "nominalCode", "name", "type", "currency", "status"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of AccountMappingOption from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict - ## Unknown currencies + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of AccountMappingOption from a dict""" + if obj is None: + return None - In line with the ISO 4217 specification, the code _XXX_ is used when the data source does not return a currency for a transaction. + if not isinstance(obj, dict): + return cls.model_validate(obj) - There are only a very small number of edge cases where this currency code is returned by the Codat system. - """ + _obj = cls.model_validate({ + "sourceModifiedDate": obj.get("sourceModifiedDate"), + "id": obj.get("id"), + "nominalCode": obj.get("nominalCode"), + "name": obj.get("name"), + "type": obj.get("type"), + "currency": obj.get("currency"), + "status": obj.get("status") + }) + return _obj - status: Optional[AccountStatus] = None - r"""The current status of the account.""" - source_modified_date: Annotated[ - Optional[str], pydantic.Field(alias="sourceModifiedDate") - ] = None - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "id", - "nominalCode", - "name", - "type", - "currency", - "status", - "sourceModifiedDate", - ] - ) - nullable_fields = set(["nominalCode", "name", "type"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - AccountMappingOption.model_rebuild() -except NameError: - pass + + +class AccountMappingOptionTypedDict(TypedDict): + """TypedDict variant of AccountMappingOption, for dict-literal request/response inputs.""" + source_modified_date: NotRequired[Optional[str]] + id: NotRequired[Optional[str]] + nominal_code: NotRequired[Optional[str]] + name: NotRequired[Optional[str]] + type: NotRequired[Optional[str]] + currency: NotRequired[Optional[str]] + status: NotRequired[Optional[AccountStatus]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/accountstatus.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/accountstatus.py index 5f3a1eff9..d26c9c752 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/accountstatus.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/accountstatus.py @@ -1,11 +1,38 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations +import json from enum import Enum +from typing_extensions import Self class AccountStatus(str, Enum): - r"""The current status of the account.""" + """ + The current status of the account. + """ + + """ + allowed enum values + """ + ACTIVE = 'Active' + ARCHIVED = 'Archived' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of AccountStatus from a JSON string""" + return cls(json.loads(json_str)) + - ACTIVE = "Active" - ARCHIVED = "Archived" diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/address.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/address.py index c54556b59..63ad4fdd2 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/address.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/address.py @@ -1,92 +1,123 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .addresstype import AddressType -from codat_sync_for_payables.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Bill pay (synchronous solution) + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 -class AddressTypedDict(TypedDict): - type: NotRequired[AddressType] - r"""The type of the address""" - line1: NotRequired[Nullable[str]] - r"""Line 1 of the customer address.""" - line2: NotRequired[Nullable[str]] - r"""Line 2 of the customer address.""" - city: NotRequired[Nullable[str]] - r"""City of the customer address.""" - region: NotRequired[Nullable[str]] - r"""Region of the customer address.""" - country: NotRequired[Nullable[str]] - r"""Country of the address. We recommend using the 2-digit ISO 3166 country code (e.g. `GB`, `US`, `FR`) as this is accepted by all supported platforms.""" - postal_code: NotRequired[Nullable[str]] - r"""Postal code or zip code.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_sync_for_payables.models.shared.addresstype import AddressType +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict +from codat_sync_for_payables.types import OptionalNullable, UNSET, UNSET_SENTINEL class Address(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'city', 'country', 'line1', 'line2', 'postalCode', 'postal_code', 'region'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + Address + """ # noqa: E501 type: Optional[AddressType] = None - r"""The type of the address""" + line1: OptionalNullable[str] = Field(default=UNSET, description="Line 1 of the customer address.") + line2: OptionalNullable[str] = Field(default=UNSET, description="Line 2 of the customer address.") + city: OptionalNullable[str] = Field(default=UNSET, description="City of the customer address.") + region: OptionalNullable[str] = Field(default=UNSET, description="Region of the customer address.") + country: OptionalNullable[str] = Field(default=UNSET, description="Country of the address. We recommend using the 2-digit ISO 3166 country code (e.g. `GB`, `US`, `FR`) as this is accepted by all supported platforms.") + postal_code: OptionalNullable[str] = Field(default=UNSET, description="Postal code or zip code.", alias="postalCode") + __properties: ClassVar[List[str]] = ["type", "line1", "line2", "city", "region", "country", "postalCode"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Address from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict - line1: OptionalNullable[str] = UNSET - r"""Line 1 of the customer address.""" + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Address from a dict""" + if obj is None: + return None - line2: OptionalNullable[str] = UNSET - r"""Line 2 of the customer address.""" + if not isinstance(obj, dict): + return cls.model_validate(obj) - city: OptionalNullable[str] = UNSET - r"""City of the customer address.""" + _obj = cls.model_validate({ + "type": obj.get("type"), + "line1": obj.get("line1"), + "line2": obj.get("line2"), + "city": obj.get("city"), + "region": obj.get("region"), + "country": obj.get("country"), + "postalCode": obj.get("postalCode") + }) + return _obj - region: OptionalNullable[str] = UNSET - r"""Region of the customer address.""" - country: OptionalNullable[str] = UNSET - r"""Country of the address. We recommend using the 2-digit ISO 3166 country code (e.g. `GB`, `US`, `FR`) as this is accepted by all supported platforms.""" - postal_code: Annotated[ - OptionalNullable[str], pydantic.Field(alias="postalCode") - ] = UNSET - r"""Postal code or zip code.""" - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - ["type", "line1", "line2", "city", "region", "country", "postalCode"] - ) - nullable_fields = set( - ["line1", "line2", "city", "region", "country", "postalCode"] - ) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - Address.model_rebuild() -except NameError: - pass + +class AddressTypedDict(TypedDict): + """TypedDict variant of Address, for dict-literal request/response inputs.""" + type: NotRequired[Optional[AddressType]] + line1: NotRequired[Optional[str]] + line2: NotRequired[Optional[str]] + city: NotRequired[Optional[str]] + region: NotRequired[Optional[str]] + country: NotRequired[Optional[str]] + postal_code: NotRequired[Optional[str]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/addresstype.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/addresstype.py index 05cc759d8..e4b105fcb 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/addresstype.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/addresstype.py @@ -1,12 +1,39 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations +import json from enum import Enum +from typing_extensions import Self class AddressType(str, Enum): - r"""The type of the address""" + """ + The type of the address + """ + + """ + allowed enum values + """ + UNKNOWN = 'Unknown' + BILLING = 'Billing' + DELIVERY = 'Delivery' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of AddressType from a JSON string""" + return cls(json.loads(json_str)) + - UNKNOWN = "Unknown" - BILLING = "Billing" - DELIVERY = "Delivery" diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/attachment.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/attachment.py index 4caea3972..7d70c4d2c 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/attachment.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/attachment.py @@ -1,181 +1,122 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_payables.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class AttachmentTypedDict(TypedDict): - r"""The Codat API supports pulling and pushing of file attachments for invoices, bills, direct costs, and direct incomes. +""" + Bill pay (synchronous solution) - > **Retrieving attachments** - > - > If a company is authorized, you can query the Codat API to read, download, and upload attachments without requiring a fresh sync of data. + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | - Unlike other data types, Codat doesn't support [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings) for attachments. + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - Note that different integrations have different requirements for file size and extension of attachments. + Do not edit the class manually. +""" # noqa: E501 - | Integration | File size | File extension | - |-------------------|-----------|--------------------------------------------------------------------------------------------------------------------------------------------------------------| - | Xero | 4 MB | 7Z, BMP, CSV, DOC, DOCX, EML, GIF, JPEG, JPG, KEYNOTE, MSG, NUMBERS, ODF, ODS, ODT, PAGES, PDF, PNG, PPT, PPTX, RAR, RTF, TIF, TIFF, TXT, XLS, XLSX, ZIP | - | QuickBooks Online | 100 MB | AI, CSV, DOC, DOCX, EPS, GIF, JPEG, JPG, ODS, PAGES, PDF, PNG, RTF, TIF, TXT, XLS, XLSX, XML | - | NetSuite | 100 MB | BMP, CSV, XLS, XLSX, JSON, PDF, PJPG, PJPEG, PNG, TXT, SVG, TIF, TIFF, DOC, DOCX, ZIP | - | Dynamics 365 Business Central | 350 MB | Dynamics do not explicitly outline which file types are supported but they do state here that \"You can attach any type of file, such as text, image, or video files\". | - """ - - id: NotRequired[str] - r"""Identifier for the attachment, unique for the company in the accounting software.""" - name: NotRequired[Nullable[str]] - r"""Name of the attachment file.""" - content_type: NotRequired[Nullable[str]] - r"""File type of the attachment. This is represented by appending the file type to the [IETF standard file naming requirements](https://tools.ietf.org/html/rfc6838). For example, for a jpeg file the output is **image/jpeg**. - - Supported file types vary per platform. - """ - date_created: NotRequired[str] - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` - - - - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - file_size: NotRequired[Nullable[int]] - r"""File size in bytes. For example, if this reads **46153**, then the file size is 46kb.""" - include_when_sent: NotRequired[bool] - r"""If `true`, then the attachment is included with the associated invoice, bill or direct costs when it is printed, emailed, or sent to a customer, if the underlying accounting software allows this.""" - source_modified_date: NotRequired[str] +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict +from codat_sync_for_payables.types import OptionalNullable, UNSET, UNSET_SENTINEL class Attachment(BaseModel): - r"""The Codat API supports pulling and pushing of file attachments for invoices, bills, direct costs, and direct incomes. - > **Retrieving attachments** - > - > If a company is authorized, you can query the Codat API to read, download, and upload attachments without requiring a fresh sync of data. - - Unlike other data types, Codat doesn't support [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings) for attachments. - - Note that different integrations have different requirements for file size and extension of attachments. - - | Integration | File size | File extension | - |-------------------|-----------|--------------------------------------------------------------------------------------------------------------------------------------------------------------| - | Xero | 4 MB | 7Z, BMP, CSV, DOC, DOCX, EML, GIF, JPEG, JPG, KEYNOTE, MSG, NUMBERS, ODF, ODS, ODT, PAGES, PDF, PNG, PPT, PPTX, RAR, RTF, TIF, TIFF, TXT, XLS, XLSX, ZIP | - | QuickBooks Online | 100 MB | AI, CSV, DOC, DOCX, EPS, GIF, JPEG, JPG, ODS, PAGES, PDF, PNG, RTF, TIF, TXT, XLS, XLSX, XML | - | NetSuite | 100 MB | BMP, CSV, XLS, XLSX, JSON, PDF, PJPG, PJPEG, PNG, TXT, SVG, TIF, TIFF, DOC, DOCX, ZIP | - | Dynamics 365 Business Central | 350 MB | Dynamics do not explicitly outline which file types are supported but they do state here that \"You can attach any type of file, such as text, image, or video files\". | + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'contentType', 'content_type', 'fileSize', 'file_size', 'name'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } """ + The Codat API supports pulling and pushing of file attachments for invoices, bills, direct costs, and direct incomes. > **Retrieving attachments** > > If a company is authorized, you can query the Codat API to read, download, and upload attachments without requiring a fresh sync of data. Unlike other data types, Codat doesn't support [sync settings](https://docs.codat.io/knowledge-base/advanced-sync-settings) for attachments. Note that different integrations have different requirements for file size and extension of attachments. | Integration | File size | File extension | |-------------------|-----------|--------------------------------------------------------------------------------------------------------------------------------------------------------------| | Xero | 4 MB | 7Z, BMP, CSV, DOC, DOCX, EML, GIF, JPEG, JPG, KEYNOTE, MSG, NUMBERS, ODF, ODS, ODT, PAGES, PDF, PNG, PPT, PPTX, RAR, RTF, TIF, TIFF, TXT, XLS, XLSX, ZIP | | QuickBooks Online | 100 MB | AI, CSV, DOC, DOCX, EPS, GIF, JPEG, JPG, ODS, PAGES, PDF, PNG, RTF, TIF, TXT, XLS, XLSX, XML | | NetSuite | 100 MB | BMP, CSV, XLS, XLSX, JSON, PDF, PJPG, PJPEG, PNG, TXT, SVG, TIF, TIFF, DOC, DOCX, ZIP | | Dynamics 365 Business Central | 350 MB | Dynamics do not explicitly outline which file types are supported but they do state here that \"You can attach any type of file, such as text, image, or video files\". | + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Identifier for the attachment, unique for the company in the accounting software.") + name: OptionalNullable[str] = Field(default=UNSET, description="Name of the attachment file.") + content_type: OptionalNullable[str] = Field(default=UNSET, description="File type of the attachment. This is represented by appending the file type to the [IETF standard file naming requirements](https://tools.ietf.org/html/rfc6838). For example, for a jpeg file the output is **image/jpeg**. Supported file types vary per platform.", alias="contentType") + date_created: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.", alias="dateCreated") + file_size: OptionalNullable[int] = Field(default=UNSET, description="File size in bytes. For example, if this reads **46153**, then the file size is 46kb.", alias="fileSize") + include_when_sent: Optional[bool] = Field(default=None, description="If `true`, then the attachment is included with the associated invoice, bill or direct costs when it is printed, emailed, or sent to a customer, if the underlying accounting software allows this.", alias="includeWhenSent") + source_modified_date: Optional[str] = Field(default=None, description="The date when a record was last modified in the accounting software, usually by the business or a business process. For example, when payments are made against an invoice. It is not populated ([read more](https://docs.codat.io/using-the-api/modified-dates#source-modified-date)) when: - Pulling attachments - The accounting software does not provide modification dates for a data type - A record has been deleted from the source platform and Codat doesn't have a record of when the deletion occurred - A record has been voided. For certain platforms that soft delete records, `isDeleted` metadata is used to identify void records In Codat's data model, dates and times are represented using the ISO 8601 standard.", alias="sourceModifiedDate") + __properties: ClassVar[List[str]] = ["id", "name", "contentType", "dateCreated", "fileSize", "includeWhenSent", "sourceModifiedDate"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) - id: Optional[str] = None - r"""Identifier for the attachment, unique for the company in the accounting software.""" - name: OptionalNullable[str] = UNSET - r"""Name of the attachment file.""" + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - content_type: Annotated[ - OptionalNullable[str], pydantic.Field(alias="contentType") - ] = UNSET - r"""File type of the attachment. This is represented by appending the file type to the [IETF standard file naming requirements](https://tools.ietf.org/html/rfc6838). For example, for a jpeg file the output is **image/jpeg**. + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - Supported file types vary per platform. - """ + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Attachment from a JSON string""" + return cls.from_dict(json.loads(json_str)) - date_created: Annotated[Optional[str], pydantic.Field(alias="dateCreated")] = None - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Attachment from a dict""" + if obj is None: + return None - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` + if not isinstance(obj, dict): + return cls.model_validate(obj) - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name"), + "contentType": obj.get("contentType"), + "dateCreated": obj.get("dateCreated"), + "fileSize": obj.get("fileSize"), + "includeWhenSent": obj.get("includeWhenSent"), + "sourceModifiedDate": obj.get("sourceModifiedDate") + }) + return _obj - file_size: Annotated[OptionalNullable[int], pydantic.Field(alias="fileSize")] = ( - UNSET - ) - r"""File size in bytes. For example, if this reads **46153**, then the file size is 46kb.""" - include_when_sent: Annotated[ - Optional[bool], pydantic.Field(alias="includeWhenSent") - ] = None - r"""If `true`, then the attachment is included with the associated invoice, bill or direct costs when it is printed, emailed, or sent to a customer, if the underlying accounting software allows this.""" - source_modified_date: Annotated[ - Optional[str], pydantic.Field(alias="sourceModifiedDate") - ] = None - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "id", - "name", - "contentType", - "dateCreated", - "fileSize", - "includeWhenSent", - "sourceModifiedDate", - ] - ) - nullable_fields = set(["name", "contentType", "fileSize"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - Attachment.model_rebuild() -except NameError: - pass + +class AttachmentTypedDict(TypedDict): + """TypedDict variant of Attachment, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + name: NotRequired[Optional[str]] + content_type: NotRequired[Optional[str]] + date_created: NotRequired[Optional[str]] + file_size: NotRequired[Optional[int]] + include_when_sent: NotRequired[Optional[bool]] + source_modified_date: NotRequired[Optional[str]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/attachmentupload.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/attachmentupload.py index b53e491ed..9c52de700 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/attachmentupload.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/attachmentupload.py @@ -1,19 +1,30 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 +"""Multipart attachment-upload body — Speakeasy wraps the uploaded file in this +shape (`attachment_upload.file` is a CodatFile).""" from __future__ import annotations -from .codatfile import CodatFile, CodatFileTypedDict -from codat_sync_for_payables.types import BaseModel -from codat_sync_for_payables.utils import FieldMetadata, MultipartFormMetadata -from typing_extensions import Annotated, TypedDict +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing_extensions import NotRequired, TypedDict -class AttachmentUploadTypedDict(TypedDict): - file: CodatFileTypedDict - r"""The file to be uploaded as an attachment.""" +from codat_sync_for_payables.models.shared.codatfile import CodatFile, CodatFileTypedDict class AttachmentUpload(BaseModel): - file: Annotated[ - CodatFile, FieldMetadata(multipart=MultipartFormMetadata(file=True)) - ] - r"""The file to be uploaded as an attachment.""" + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + + file: CodatFile = Field(description="The file to be uploaded as an attachment.") + + model_config = ConfigDict( + populate_by_name=True, + arbitrary_types_allowed=True, + protected_namespaces=(), + ) + + +class AttachmentUploadTypedDict(TypedDict): + file: CodatFileTypedDict diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/bankaccount.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/bankaccount.py index 4747806ae..ad430bf02 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/bankaccount.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/bankaccount.py @@ -1,153 +1,130 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .bankaccountstatus import BankAccountStatus -from .bankaccounttype import BankAccountType -from codat_sync_for_payables.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Bill pay (synchronous solution) + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | -class BankAccountTypedDict(TypedDict): - id: NotRequired[str] - r"""Identifier for the bank account, unique for the company in the accounting software.""" - nominal_code: NotRequired[Nullable[str]] - r"""Code used to identify each nominal account for a business.""" - name: NotRequired[Nullable[str]] - r"""Name of the bank account in the accounting software.""" - account_type: NotRequired[BankAccountType] - r"""The type of transactions and balances on the account. - For Credit accounts, positive balances are liabilities, and positive transactions **reduce** liabilities. - For Debit accounts, positive balances are assets, and positive transactions **increase** assets. - """ - account_number: NotRequired[Nullable[str]] - r"""Account number for the bank account. + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - Xero integrations - Only a UK account number shows for bank accounts with GBP currency and a combined total of sort code and account number that equals 14 digits, For non-GBP accounts, the full bank account number is populated. - """ - sort_code: NotRequired[Nullable[str]] - r"""Sort code for the bank account. This is relevant to UK bank accounts. + Do not edit the class manually. +""" # noqa: E501 - Xero integrations - The sort code is only displayed when the currency = GBP and the sort code and account number sum to 14 digits. For non-GBP accounts, this field is not populated. + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_sync_for_payables.models.shared.bankaccountstatus import BankAccountStatus +from codat_sync_for_payables.models.shared.bankaccounttype import BankAccountType +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_sync_for_payables.types import OptionalNullable, UNSET, UNSET_SENTINEL +class BankAccount(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'accountNumber', 'account_number', 'name', 'nominalCode', 'nominal_code', 'sortCode', 'sort_code'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } """ - currency: NotRequired[str] - r"""The currency data type in Codat is the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code, e.g. _GBP_. + BankAccount + """ # noqa: E501 + source_modified_date: Optional[str] = Field(default=None, description="The date when a record was last modified in the accounting software, usually by the business or a business process. For example, when payments are made against an invoice. It is not populated ([read more](https://docs.codat.io/using-the-api/modified-dates#source-modified-date)) when: - Pulling attachments - The accounting software does not provide modification dates for a data type - A record has been deleted from the source platform and Codat doesn't have a record of when the deletion occurred - A record has been voided. For certain platforms that soft delete records, `isDeleted` metadata is used to identify void records In Codat's data model, dates and times are represented using the ISO 8601 standard.", alias="sourceModifiedDate") + id: Optional[str] = Field(default=None, description="Identifier for the bank account, unique for the company in the accounting software.") + nominal_code: OptionalNullable[str] = Field(default=UNSET, description="Code used to identify each nominal account for a business.", alias="nominalCode") + name: OptionalNullable[str] = Field(default=UNSET, description="Name of the bank account in the accounting software.") + account_type: Optional[BankAccountType] = Field(default=None, alias="accountType") + account_number: OptionalNullable[str] = Field(default=UNSET, description="Account number for the bank account. Xero integrations Only a UK account number shows for bank accounts with GBP currency and a combined total of sort code and account number that equals 14 digits, For non-GBP accounts, the full bank account number is populated.", alias="accountNumber") + sort_code: OptionalNullable[str] = Field(default=UNSET, description="Sort code for the bank account. This is relevant to UK bank accounts. Xero integrations The sort code is only displayed when the currency = GBP and the sort code and account number sum to 14 digits. For non-GBP accounts, this field is not populated.", alias="sortCode") + currency: Optional[str] = Field(default=None, description="The currency data type in Codat is the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code, e.g. _GBP_. ## Unknown currencies In line with the ISO 4217 specification, the code _XXX_ is used when the data source does not return a currency for a transaction. There are only a very small number of edge cases where this currency code is returned by the Codat system.") + status: Optional[BankAccountStatus] = None + __properties: ClassVar[List[str]] = ["sourceModifiedDate", "id", "nominalCode", "name", "accountType", "accountNumber", "sortCode", "currency", "status"] - ## Unknown currencies + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) - In line with the ISO 4217 specification, the code _XXX_ is used when the data source does not return a currency for a transaction. - There are only a very small number of edge cases where this currency code is returned by the Codat system. - """ - status: NotRequired[BankAccountStatus] - r"""The current status of the bank account.""" - source_modified_date: NotRequired[str] + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) -class BankAccount(BaseModel): - id: Optional[str] = None - r"""Identifier for the bank account, unique for the company in the accounting software.""" - - nominal_code: Annotated[ - OptionalNullable[str], pydantic.Field(alias="nominalCode") - ] = UNSET - r"""Code used to identify each nominal account for a business.""" - - name: OptionalNullable[str] = UNSET - r"""Name of the bank account in the accounting software.""" - - account_type: Annotated[ - Optional[BankAccountType], pydantic.Field(alias="accountType") - ] = None - r"""The type of transactions and balances on the account. - For Credit accounts, positive balances are liabilities, and positive transactions **reduce** liabilities. - For Debit accounts, positive balances are assets, and positive transactions **increase** assets. - """ + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of BankAccount from a JSON string""" + return cls.from_dict(json.loads(json_str)) - account_number: Annotated[ - OptionalNullable[str], pydantic.Field(alias="accountNumber") - ] = UNSET - r"""Account number for the bank account. + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - Xero integrations - Only a UK account number shows for bank accounts with GBP currency and a combined total of sort code and account number that equals 14 digits, For non-GBP accounts, the full bank account number is populated. - """ + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - sort_code: Annotated[OptionalNullable[str], pydantic.Field(alias="sortCode")] = ( - UNSET - ) - r"""Sort code for the bank account. This is relevant to UK bank accounts. + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) - Xero integrations - The sort code is only displayed when the currency = GBP and the sort code and account number sum to 14 digits. For non-GBP accounts, this field is not populated. - """ + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict - currency: Optional[str] = None - r"""The currency data type in Codat is the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code, e.g. _GBP_. + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of BankAccount from a dict""" + if obj is None: + return None - ## Unknown currencies + if not isinstance(obj, dict): + return cls.model_validate(obj) - In line with the ISO 4217 specification, the code _XXX_ is used when the data source does not return a currency for a transaction. + _obj = cls.model_validate({ + "sourceModifiedDate": obj.get("sourceModifiedDate"), + "id": obj.get("id"), + "nominalCode": obj.get("nominalCode"), + "name": obj.get("name"), + "accountType": obj.get("accountType"), + "accountNumber": obj.get("accountNumber"), + "sortCode": obj.get("sortCode"), + "currency": obj.get("currency"), + "status": obj.get("status") + }) + return _obj - There are only a very small number of edge cases where this currency code is returned by the Codat system. - """ - status: Optional[BankAccountStatus] = None - r"""The current status of the bank account.""" - source_modified_date: Annotated[ - Optional[str], pydantic.Field(alias="sourceModifiedDate") - ] = None - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "id", - "nominalCode", - "name", - "accountType", - "accountNumber", - "sortCode", - "currency", - "status", - "sourceModifiedDate", - ] - ) - nullable_fields = set(["nominalCode", "name", "accountNumber", "sortCode"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - BankAccount.model_rebuild() -except NameError: - pass + +class BankAccountTypedDict(TypedDict): + """TypedDict variant of BankAccount, for dict-literal request/response inputs.""" + source_modified_date: NotRequired[Optional[str]] + id: NotRequired[Optional[str]] + nominal_code: NotRequired[Optional[str]] + name: NotRequired[Optional[str]] + account_type: NotRequired[Optional[BankAccountType]] + account_number: NotRequired[Optional[str]] + sort_code: NotRequired[Optional[str]] + currency: NotRequired[Optional[str]] + status: NotRequired[Optional[BankAccountStatus]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/bankaccountmappingoption.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/bankaccountmappingoption.py index aa5b368f6..db4e980fc 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/bankaccountmappingoption.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/bankaccountmappingoption.py @@ -1,141 +1,130 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .bankaccountstatus import BankAccountStatus -from .bankaccounttype import BankAccountType -from codat_sync_for_payables.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Bill pay (synchronous solution) + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | -class BankAccountMappingOptionTypedDict(TypedDict): - id: NotRequired[str] - r"""Identifier for the account, unique for the company in the accounting software.""" - name: NotRequired[Nullable[str]] - r"""Name of the bank account in the accounting software.""" - account_number: NotRequired[Nullable[str]] - r"""Account number for the bank account. - - Xero integrations - Only a UK account number shows for bank accounts with GBP currency and a combined total of sort code and account number that equals 14 digits, For non-GBP accounts, the full bank account number is populated. - """ - nominal_code: NotRequired[Nullable[str]] - r"""Code used to identify each nominal account for a business.""" - sort_code: NotRequired[Nullable[str]] - r"""Sort code for the bank account. + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - Xero integrations - The sort code is only displayed when the currency = GBP and the sort code and account number sum to 14 digits. For non-GBP accounts, this field is not populated. - """ - currency: NotRequired[Nullable[str]] - r"""The bank account's base currency.""" - status: NotRequired[BankAccountStatus] - r"""The current status of the bank account.""" - account_type: NotRequired[BankAccountType] - r"""The type of transactions and balances on the account. - For Credit accounts, positive balances are liabilities, and positive transactions **reduce** liabilities. - For Debit accounts, positive balances are assets, and positive transactions **increase** assets. - """ - source_modified_date: NotRequired[str] + Do not edit the class manually. +""" # noqa: E501 +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_sync_for_payables.models.shared.bankaccountstatus import BankAccountStatus +from codat_sync_for_payables.models.shared.bankaccounttype import BankAccountType +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_sync_for_payables.types import OptionalNullable, UNSET, UNSET_SENTINEL class BankAccountMappingOption(BaseModel): - id: Optional[str] = None - r"""Identifier for the account, unique for the company in the accounting software.""" - name: OptionalNullable[str] = UNSET - r"""Name of the bank account in the accounting software.""" + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'accountNumber', 'account_number', 'currency', 'name', 'nominalCode', 'nominal_code', 'sortCode', 'sort_code'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + BankAccountMappingOption + """ # noqa: E501 + source_modified_date: Optional[str] = Field(default=None, description="The date when a record was last modified in the accounting software, usually by the business or a business process. For example, when payments are made against an invoice. It is not populated ([read more](https://docs.codat.io/using-the-api/modified-dates#source-modified-date)) when: - Pulling attachments - The accounting software does not provide modification dates for a data type - A record has been deleted from the source platform and Codat doesn't have a record of when the deletion occurred - A record has been voided. For certain platforms that soft delete records, `isDeleted` metadata is used to identify void records In Codat's data model, dates and times are represented using the ISO 8601 standard.", alias="sourceModifiedDate") + id: Optional[str] = Field(default=None, description="Identifier for the account, unique for the company in the accounting software.") + name: OptionalNullable[str] = Field(default=UNSET, description="Name of the bank account in the accounting software.") + account_number: OptionalNullable[str] = Field(default=UNSET, description="Account number for the bank account. Xero integrations Only a UK account number shows for bank accounts with GBP currency and a combined total of sort code and account number that equals 14 digits, For non-GBP accounts, the full bank account number is populated.", alias="accountNumber") + nominal_code: OptionalNullable[str] = Field(default=UNSET, description="Code used to identify each nominal account for a business.", alias="nominalCode") + sort_code: OptionalNullable[str] = Field(default=UNSET, description="Sort code for the bank account. Xero integrations The sort code is only displayed when the currency = GBP and the sort code and account number sum to 14 digits. For non-GBP accounts, this field is not populated.", alias="sortCode") + currency: OptionalNullable[str] = Field(default=UNSET, description="The bank account's base currency.") + status: Optional[BankAccountStatus] = None + account_type: Optional[BankAccountType] = Field(default=None, alias="accountType") + __properties: ClassVar[List[str]] = ["sourceModifiedDate", "id", "name", "accountNumber", "nominalCode", "sortCode", "currency", "status", "accountType"] - account_number: Annotated[ - OptionalNullable[str], pydantic.Field(alias="accountNumber") - ] = UNSET - r"""Account number for the bank account. + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) - Xero integrations - Only a UK account number shows for bank accounts with GBP currency and a combined total of sort code and account number that equals 14 digits, For non-GBP accounts, the full bank account number is populated. - """ - nominal_code: Annotated[ - OptionalNullable[str], pydantic.Field(alias="nominalCode") - ] = UNSET - r"""Code used to identify each nominal account for a business.""" + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - sort_code: Annotated[OptionalNullable[str], pydantic.Field(alias="sortCode")] = ( - UNSET - ) - r"""Sort code for the bank account. + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - Xero integrations - The sort code is only displayed when the currency = GBP and the sort code and account number sum to 14 digits. For non-GBP accounts, this field is not populated. - """ + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of BankAccountMappingOption from a JSON string""" + return cls.from_dict(json.loads(json_str)) - currency: OptionalNullable[str] = UNSET - r"""The bank account's base currency.""" + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - status: Optional[BankAccountStatus] = None - r"""The current status of the bank account.""" - - account_type: Annotated[ - Optional[BankAccountType], pydantic.Field(alias="accountType") - ] = None - r"""The type of transactions and balances on the account. - For Credit accounts, positive balances are liabilities, and positive transactions **reduce** liabilities. - For Debit accounts, positive balances are assets, and positive transactions **increase** assets. - """ + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - source_modified_date: Annotated[ - Optional[str], pydantic.Field(alias="sourceModifiedDate") - ] = None + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "id", - "name", - "accountNumber", - "nominalCode", - "sortCode", - "currency", - "status", - "accountType", - "sourceModifiedDate", - ] - ) - nullable_fields = set( - ["name", "accountNumber", "nominalCode", "sortCode", "currency"] + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, ) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - BankAccountMappingOption.model_rebuild() -except NameError: - pass + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of BankAccountMappingOption from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "sourceModifiedDate": obj.get("sourceModifiedDate"), + "id": obj.get("id"), + "name": obj.get("name"), + "accountNumber": obj.get("accountNumber"), + "nominalCode": obj.get("nominalCode"), + "sortCode": obj.get("sortCode"), + "currency": obj.get("currency"), + "status": obj.get("status"), + "accountType": obj.get("accountType") + }) + return _obj + + + + + +class BankAccountMappingOptionTypedDict(TypedDict): + """TypedDict variant of BankAccountMappingOption, for dict-literal request/response inputs.""" + source_modified_date: NotRequired[Optional[str]] + id: NotRequired[Optional[str]] + name: NotRequired[Optional[str]] + account_number: NotRequired[Optional[str]] + nominal_code: NotRequired[Optional[str]] + sort_code: NotRequired[Optional[str]] + currency: NotRequired[Optional[str]] + status: NotRequired[Optional[BankAccountStatus]] + account_type: NotRequired[Optional[BankAccountType]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/bankaccountprototype.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/bankaccountprototype.py index 919b51757..4db4bb8da 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/bankaccountprototype.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/bankaccountprototype.py @@ -1,120 +1,120 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .bankaccounttype import BankAccountType -from codat_sync_for_payables.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Bill pay (synchronous solution) + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | -class BankAccountPrototypeTypedDict(TypedDict): - name: Nullable[str] - r"""Name of the bank account in the accounting software.""" - account_type: BankAccountType - r"""The type of transactions and balances on the account. - For Credit accounts, positive balances are liabilities, and positive transactions **reduce** liabilities. - For Debit accounts, positive balances are assets, and positive transactions **increase** assets. - """ - account_number: Nullable[str] - r"""Account number for the bank account. + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - Xero integrations - Only a UK account number shows for bank accounts with GBP currency and a combined total of sort code and account number that equals 14 digits, For non-GBP accounts, the full bank account number is populated. - """ - currency: str - r"""The currency data type in Codat is the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code, e.g. _GBP_. + Do not edit the class manually. +""" # noqa: E501 - ## Unknown currencies - In line with the ISO 4217 specification, the code _XXX_ is used when the data source does not return a currency for a transaction. +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - There are only a very small number of edge cases where this currency code is returned by the Codat system. - """ - nominal_code: NotRequired[Nullable[str]] - r"""Code used to identify each nominal account for a business.""" - sort_code: NotRequired[Nullable[str]] - r"""Sort code for the bank account. This is relevant to UK bank accounts. +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_sync_for_payables.models.shared.bankaccounttype import BankAccountType +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict - Xero integrations - The sort code is only displayed when the currency = GBP and the sort code and account number sum to 14 digits. For non-GBP accounts, this field is not populated. +from codat_sync_for_payables.types import OptionalNullable, UNSET, UNSET_SENTINEL +class BankAccountPrototype(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'nominalCode', 'nominal_code', 'sortCode', 'sort_code'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } """ + BankAccountPrototype + """ # noqa: E501 + nominal_code: OptionalNullable[str] = Field(default=UNSET, description="Code used to identify each nominal account for a business.", alias="nominalCode") + name: str = Field(description="Name of the bank account in the accounting software.") + account_type: BankAccountType = Field(alias="accountType") + account_number: str = Field(description="Account number for the bank account. Xero integrations Only a UK account number shows for bank accounts with GBP currency and a combined total of sort code and account number that equals 14 digits, For non-GBP accounts, the full bank account number is populated.", alias="accountNumber") + sort_code: OptionalNullable[str] = Field(default=UNSET, description="Sort code for the bank account. This is relevant to UK bank accounts. Xero integrations The sort code is only displayed when the currency = GBP and the sort code and account number sum to 14 digits. For non-GBP accounts, this field is not populated.", alias="sortCode") + currency: str = Field(description="The currency data type in Codat is the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code, e.g. _GBP_. ## Unknown currencies In line with the ISO 4217 specification, the code _XXX_ is used when the data source does not return a currency for a transaction. There are only a very small number of edge cases where this currency code is returned by the Codat system.") + __properties: ClassVar[List[str]] = ["nominalCode", "name", "accountType", "accountNumber", "sortCode", "currency"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) -class BankAccountPrototype(BaseModel): - name: Nullable[str] - r"""Name of the bank account in the accounting software.""" + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - account_type: Annotated[BankAccountType, pydantic.Field(alias="accountType")] - r"""The type of transactions and balances on the account. - For Credit accounts, positive balances are liabilities, and positive transactions **reduce** liabilities. - For Debit accounts, positive balances are assets, and positive transactions **increase** assets. - """ + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - account_number: Annotated[Nullable[str], pydantic.Field(alias="accountNumber")] - r"""Account number for the bank account. + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of BankAccountPrototype from a JSON string""" + return cls.from_dict(json.loads(json_str)) - Xero integrations - Only a UK account number shows for bank accounts with GBP currency and a combined total of sort code and account number that equals 14 digits, For non-GBP accounts, the full bank account number is populated. - """ + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - currency: str - r"""The currency data type in Codat is the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code, e.g. _GBP_. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - ## Unknown currencies + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) - In line with the ISO 4217 specification, the code _XXX_ is used when the data source does not return a currency for a transaction. + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict - There are only a very small number of edge cases where this currency code is returned by the Codat system. - """ + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of BankAccountPrototype from a dict""" + if obj is None: + return None - nominal_code: Annotated[ - OptionalNullable[str], pydantic.Field(alias="nominalCode") - ] = UNSET - r"""Code used to identify each nominal account for a business.""" + if not isinstance(obj, dict): + return cls.model_validate(obj) - sort_code: Annotated[OptionalNullable[str], pydantic.Field(alias="sortCode")] = ( - UNSET - ) - r"""Sort code for the bank account. This is relevant to UK bank accounts. + _obj = cls.model_validate({ + "nominalCode": obj.get("nominalCode"), + "name": obj.get("name"), + "accountType": obj.get("accountType"), + "accountNumber": obj.get("accountNumber"), + "sortCode": obj.get("sortCode"), + "currency": obj.get("currency") + }) + return _obj - Xero integrations - The sort code is only displayed when the currency = GBP and the sort code and account number sum to 14 digits. For non-GBP accounts, this field is not populated. - """ - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["nominalCode", "sortCode"]) - nullable_fields = set(["nominalCode", "name", "accountNumber", "sortCode"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - BankAccountPrototype.model_rebuild() -except NameError: - pass + + + +class BankAccountPrototypeTypedDict(TypedDict): + """TypedDict variant of BankAccountPrototype, for dict-literal request/response inputs.""" + nominal_code: NotRequired[Optional[str]] + name: NotRequired[str] + account_type: NotRequired[BankAccountType] + account_number: NotRequired[str] + sort_code: NotRequired[Optional[str]] + currency: NotRequired[str] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/bankaccountstatus.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/bankaccountstatus.py index 7db267519..5537d8d50 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/bankaccountstatus.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/bankaccountstatus.py @@ -1,11 +1,38 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations +import json from enum import Enum +from typing_extensions import Self class BankAccountStatus(str, Enum): - r"""The current status of the bank account.""" + """ + The current status of the bank account. + """ + + """ + allowed enum values + """ + ACTIVE = 'Active' + ARCHIVED = 'Archived' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of BankAccountStatus from a JSON string""" + return cls(json.loads(json_str)) + - ACTIVE = "Active" - ARCHIVED = "Archived" diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/bankaccounttype.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/bankaccounttype.py index 9eecbae47..0b269c7a9 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/bankaccounttype.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/bankaccounttype.py @@ -1,15 +1,39 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations +import json from enum import Enum +from typing_extensions import Self class BankAccountType(str, Enum): - r"""The type of transactions and balances on the account. - For Credit accounts, positive balances are liabilities, and positive transactions **reduce** liabilities. - For Debit accounts, positive balances are assets, and positive transactions **increase** assets. """ + The type of transactions and balances on the account. For Credit accounts, positive balances are liabilities, and positive transactions **reduce** liabilities. For Debit accounts, positive balances are assets, and positive transactions **increase** assets. + """ + + """ + allowed enum values + """ + UNKNOWN = 'Unknown' + CREDIT = 'Credit' + DEBIT = 'Debit' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of BankAccountType from a JSON string""" + return cls(json.loads(json_str)) + - UNKNOWN = "Unknown" - CREDIT = "Credit" - DEBIT = "Debit" diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/bill.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/bill.py index 59ba9105e..53aec0577 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/bill.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/bill.py @@ -1,228 +1,152 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .billlineitem import BillLineItem, BillLineItemTypedDict -from .billstatus import BillStatus -from .supplierref import SupplierRef, SupplierRefTypedDict -from codat_sync_for_payables.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from codat_sync_for_payables.utils import serialize_decimal, validate_decimal -from decimal import Decimal -import pydantic -from pydantic import model_serializer -from pydantic.functional_serializers import PlainSerializer -from pydantic.functional_validators import BeforeValidator -from typing import List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class BillTypedDict(TypedDict): - r"""Bills are invoices that represent the SMB's financial obligations to their supplier for a purchase of goods or services.""" - - supplier_ref: SupplierRefTypedDict - r"""Reference to the supplier the record relates to.""" - issue_date: str - due_date: str - currency: str - r"""The currency data type in Codat is the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code, e.g. _GBP_. - - ## Unknown currencies - - In line with the ISO 4217 specification, the code _XXX_ is used when the data source does not return a currency for a transaction. - - There are only a very small number of edge cases where this currency code is returned by the Codat system. - """ - status: BillStatus - r"""Current state of the bill. If creating a bill the status must be `Open`.""" - id: NotRequired[str] - r"""Identifier for the bill, unique for the company in the accounting software.""" - reference: NotRequired[Nullable[str]] - r"""User-friendly reference for the bill.""" - currency_rate: NotRequired[Nullable[Decimal]] - r"""Rate to convert the total amount of the payment into the base currency for the company at the time of the payment. - - Currency rates in Codat are implemented as the multiple of foreign currency units to each base currency unit. - - It is not possible to perform the currency conversion with two or more non-base currencies participating in the transaction. For example, if a company's base currency is USD, and it has a bill issued in EUR, then the bill payment must happen in USD or EUR. +""" + Bill pay (synchronous solution) - Where the currency rate is provided by the underlying accounting software, it will be available from Codat with the same precision (up to a maximum of 9 decimal places). + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | - For accounting software which do not provide an explicit currency rate, it is calculated as `baseCurrency / foreignCurrency` and will be returned to 9 decimal places. + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - ## Examples with base currency of GBP - - | Foreign Currency | Foreign Amount | Currency Rate | Base Currency Amount (GBP) | - | :--------------- | :------------- | :------------ | :------------------------- | - | **USD** | $20 | 0.781 | £15.62 | - | **EUR** | €20 | 0.885 | £17.70 | - | **RUB** | ₽20 | 0.011 | £0.22 | - - ## Examples with base currency of USD - - | Foreign Currency | Foreign Amount | Currency Rate | Base Currency Amount (USD) | - | :--------------- | :------------- | :------------ | :------------------------- | - | **GBP** | £20 | 1.277 | $25.54 | - | **EUR** | €20 | 1.134 | $22.68 | - | **RUB** | ₽20 | 0.015 | $0.30 | - - - ### Integration-specific details - - | Integration | Scenario | System behavior | - |-------------------|-------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| - | QuickBooks Online | Transaction currency differs from base currency | If currency rate value is left `null`, a rate of 1 will be used by QBO by default. To override this, specify a currencyRate in the request body. | - """ - line_items: NotRequired[Nullable[List[BillLineItemTypedDict]]] - r"""Array of Bill line items.""" - total_amount: NotRequired[Decimal] - r"""Amount of the bill, including tax.""" - amount_due: NotRequired[Nullable[Decimal]] - r"""Amount outstanding on the bill.""" - source_modified_date: NotRequired[str] + Do not edit the class manually. +""" # noqa: E501 +from __future__ import annotations +from decimal import Decimal +from codat_sync_for_payables.utils.serializers import serialize_decimal, validate_decimal +import pprint +import re # noqa: F401 +import json + +from pydantic import BeforeValidator, PlainSerializer, BaseModel, ConfigDict, Field, model_serializer +from typing import Annotated, Any, ClassVar, Dict, List, Optional, Union +from codat_sync_for_payables.models.shared.billlineitem import BillLineItem, BillLineItemTypedDict +from codat_sync_for_payables.models.shared.billstatus import BillStatus +from codat_sync_for_payables.models.shared.supplierref import SupplierRef, SupplierRefTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_sync_for_payables.types import OptionalNullable, UNSET, UNSET_SENTINEL class Bill(BaseModel): - r"""Bills are invoices that represent the SMB's financial obligations to their supplier for a purchase of goods or services.""" - - supplier_ref: Annotated[SupplierRef, pydantic.Field(alias="supplierRef")] - r"""Reference to the supplier the record relates to.""" - - issue_date: Annotated[str, pydantic.Field(alias="issueDate")] - - due_date: Annotated[str, pydantic.Field(alias="dueDate")] - currency: str - r"""The currency data type in Codat is the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code, e.g. _GBP_. - - ## Unknown currencies - - In line with the ISO 4217 specification, the code _XXX_ is used when the data source does not return a currency for a transaction. - - There are only a very small number of edge cases where this currency code is returned by the Codat system. + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'amountDue', 'amount_due', 'currencyRate', 'currency_rate', 'lineItems', 'line_items', 'reference'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } """ - + Bills are invoices that represent the SMB's financial obligations to their supplier for a purchase of goods or services. + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Identifier for the bill, unique for the company in the accounting software.") + reference: OptionalNullable[str] = Field(default=UNSET, description="User-friendly reference for the bill.") + supplier_ref: SupplierRef = Field(alias="supplierRef") + issue_date: str = Field(description="Date of the bill as recorded in the accounting software.", alias="issueDate") + due_date: str = Field(description="Date the supplier is due to be paid.", alias="dueDate") + currency: str = Field(description="The currency data type in Codat is the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code, e.g. _GBP_. ## Unknown currencies In line with the ISO 4217 specification, the code _XXX_ is used when the data source does not return a currency for a transaction. There are only a very small number of edge cases where this currency code is returned by the Codat system.") + currency_rate: Annotated[OptionalNullable[Decimal], BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(default=UNSET, description="Rate to convert the total amount of the payment into the base currency for the company at the time of the payment. Currency rates in Codat are implemented as the multiple of foreign currency units to each base currency unit. It is not possible to perform the currency conversion with two or more non-base currencies participating in the transaction. For example, if a company's base currency is USD, and it has a bill issued in EUR, then the bill payment must happen in USD or EUR. Where the currency rate is provided by the underlying accounting software, it will be available from Codat with the same precision (up to a maximum of 9 decimal places). For accounting software which do not provide an explicit currency rate, it is calculated as `baseCurrency / foreignCurrency` and will be returned to 9 decimal places. ## Examples with base currency of GBP | Foreign Currency | Foreign Amount | Currency Rate | Base Currency Amount (GBP) | | :--------------- | :------------- | :------------ | :------------------------- | | **USD** | $20 | 0.781 | £15.62 | | **EUR** | €20 | 0.885 | £17.70 | | **RUB** | ₽20 | 0.011 | £0.22 | ## Examples with base currency of USD | Foreign Currency | Foreign Amount | Currency Rate | Base Currency Amount (USD) | | :--------------- | :------------- | :------------ | :------------------------- | | **GBP** | £20 | 1.277 | $25.54 | | **EUR** | €20 | 1.134 | $22.68 | | **RUB** | ₽20 | 0.015 | $0.30 | ### Integration-specific details | Integration | Scenario | System behavior | |-------------------|-------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| | QuickBooks Online | Transaction currency differs from base currency | If currency rate value is left `null`, a rate of 1 will be used by QBO by default. To override this, specify a currencyRate in the request body. |", alias="currencyRate") + line_items: OptionalNullable[List[BillLineItem]] = Field(default=UNSET, description="Array of Bill line items.", alias="lineItems") status: BillStatus - r"""Current state of the bill. If creating a bill the status must be `Open`.""" - - id: Optional[str] = None - r"""Identifier for the bill, unique for the company in the accounting software.""" - - reference: OptionalNullable[str] = UNSET - r"""User-friendly reference for the bill.""" - - currency_rate: Annotated[ - Annotated[ - OptionalNullable[Decimal], - BeforeValidator(validate_decimal), - PlainSerializer(serialize_decimal(False)), - ], - pydantic.Field(alias="currencyRate"), - ] = UNSET - r"""Rate to convert the total amount of the payment into the base currency for the company at the time of the payment. - - Currency rates in Codat are implemented as the multiple of foreign currency units to each base currency unit. - - It is not possible to perform the currency conversion with two or more non-base currencies participating in the transaction. For example, if a company's base currency is USD, and it has a bill issued in EUR, then the bill payment must happen in USD or EUR. - - Where the currency rate is provided by the underlying accounting software, it will be available from Codat with the same precision (up to a maximum of 9 decimal places). - - For accounting software which do not provide an explicit currency rate, it is calculated as `baseCurrency / foreignCurrency` and will be returned to 9 decimal places. - - ## Examples with base currency of GBP - - | Foreign Currency | Foreign Amount | Currency Rate | Base Currency Amount (GBP) | - | :--------------- | :------------- | :------------ | :------------------------- | - | **USD** | $20 | 0.781 | £15.62 | - | **EUR** | €20 | 0.885 | £17.70 | - | **RUB** | ₽20 | 0.011 | £0.22 | - - ## Examples with base currency of USD - - | Foreign Currency | Foreign Amount | Currency Rate | Base Currency Amount (USD) | - | :--------------- | :------------- | :------------ | :------------------------- | - | **GBP** | £20 | 1.277 | $25.54 | - | **EUR** | €20 | 1.134 | $22.68 | - | **RUB** | ₽20 | 0.015 | $0.30 | + total_amount: Annotated[Optional[Decimal], BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(default=None, description="Amount of the bill, including tax.", alias="totalAmount") + amount_due: Annotated[OptionalNullable[Decimal], BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(default=UNSET, description="Amount outstanding on the bill.", alias="amountDue") + source_modified_date: Optional[str] = Field(default=None, description="The date when a record was last modified in the accounting software, usually by the business or a business process. For example, when payments are made against an invoice. It is not populated ([read more](https://docs.codat.io/using-the-api/modified-dates#source-modified-date)) when: - Pulling attachments - The accounting software does not provide modification dates for a data type - A record has been deleted from the source platform and Codat doesn't have a record of when the deletion occurred - A record has been voided. For certain platforms that soft delete records, `isDeleted` metadata is used to identify void records In Codat's data model, dates and times are represented using the ISO 8601 standard.", alias="sourceModifiedDate") + __properties: ClassVar[List[str]] = ["id", "reference", "supplierRef", "issueDate", "dueDate", "currency", "currencyRate", "lineItems", "status", "totalAmount", "amountDue", "sourceModifiedDate"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Bill from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of supplier_ref + if self.supplier_ref: + _dict['supplierRef'] = self.supplier_ref.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in line_items (list) + _items = [] + if self.line_items: + for _item_line_items in self.line_items: + if _item_line_items: + _items.append(_item_line_items.to_dict()) + _dict['lineItems'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Bill from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "reference": obj.get("reference"), + "supplierRef": SupplierRef.from_dict(obj["supplierRef"]) if obj.get("supplierRef") is not None else None, + "issueDate": obj.get("issueDate"), + "dueDate": obj.get("dueDate"), + "currency": obj.get("currency"), + "currencyRate": obj.get("currencyRate"), + "lineItems": [BillLineItem.from_dict(_item) for _item in obj["lineItems"]] if obj.get("lineItems") is not None else None, + "status": obj.get("status"), + "totalAmount": obj.get("totalAmount"), + "amountDue": obj.get("amountDue"), + "sourceModifiedDate": obj.get("sourceModifiedDate") + }) + return _obj - ### Integration-specific details - | Integration | Scenario | System behavior | - |-------------------|-------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| - | QuickBooks Online | Transaction currency differs from base currency | If currency rate value is left `null`, a rate of 1 will be used by QBO by default. To override this, specify a currencyRate in the request body. | - """ - line_items: Annotated[ - OptionalNullable[List[BillLineItem]], pydantic.Field(alias="lineItems") - ] = UNSET - r"""Array of Bill line items.""" - - total_amount: Annotated[ - Annotated[ - Optional[Decimal], - BeforeValidator(validate_decimal), - PlainSerializer(serialize_decimal(False)), - ], - pydantic.Field(alias="totalAmount"), - ] = None - r"""Amount of the bill, including tax.""" - - amount_due: Annotated[ - Annotated[ - OptionalNullable[Decimal], - BeforeValidator(validate_decimal), - PlainSerializer(serialize_decimal(False)), - ], - pydantic.Field(alias="amountDue"), - ] = UNSET - r"""Amount outstanding on the bill.""" - - source_modified_date: Annotated[ - Optional[str], pydantic.Field(alias="sourceModifiedDate") - ] = None - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "id", - "reference", - "currencyRate", - "lineItems", - "totalAmount", - "amountDue", - "sourceModifiedDate", - ] - ) - nullable_fields = set(["reference", "currencyRate", "lineItems", "amountDue"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - Bill.model_rebuild() -except NameError: - pass +class BillTypedDict(TypedDict): + """TypedDict variant of Bill, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + reference: NotRequired[Optional[str]] + supplier_ref: NotRequired[SupplierRefTypedDict] + issue_date: NotRequired[str] + due_date: NotRequired[str] + currency: NotRequired[str] + currency_rate: NotRequired[Optional[Decimal]] + line_items: NotRequired[Optional[List[BillLineItemTypedDict]]] + status: BillStatus + total_amount: NotRequired[Optional[Decimal]] + amount_due: NotRequired[Optional[Decimal]] + source_modified_date: NotRequired[Optional[str]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/billaccountref.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/billaccountref.py index 9923de327..b4199559c 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/billaccountref.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/billaccountref.py @@ -1,37 +1,99 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_payables.types import BaseModel, UNSET_SENTINEL -from pydantic import model_serializer -from typing import Optional -from typing_extensions import NotRequired, TypedDict +""" + Bill pay (synchronous solution) + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | -class BillAccountRefTypedDict(TypedDict): - r"""Reference to the account to which the line item is linked.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - id: NotRequired[str] - r"""'id' from the Accounts data type.""" + Do not edit the class manually. +""" # noqa: E501 -class BillAccountRef(BaseModel): - r"""Reference to the account to which the line item is linked.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict - id: Optional[str] = None - r"""'id' from the Accounts data type.""" +class BillAccountRef(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["id"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + Reference to the account to which the line item is linked. + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="'id' from the Accounts data type.") + __properties: ClassVar[List[str]] = ["id"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of BillAccountRef from a JSON string""" + return cls.from_dict(json.loads(json_str)) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - return m + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of BillAccountRef from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id") + }) + return _obj + + + + + +class BillAccountRefTypedDict(TypedDict): + """TypedDict variant of BillAccountRef, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/billlineitem.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/billlineitem.py index 49c500e89..ea0e10fba 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/billlineitem.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/billlineitem.py @@ -1,137 +1,143 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .billaccountref import BillAccountRef, BillAccountRefTypedDict -from .billtaxrateref import BillTaxRateRef, BillTaxRateRefTypedDict -from .trackingref import TrackingRef, TrackingRefTypedDict -from codat_sync_for_payables.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from codat_sync_for_payables.utils import serialize_decimal, validate_decimal -from decimal import Decimal -import pydantic -from pydantic import model_serializer -from pydantic.functional_serializers import PlainSerializer -from pydantic.functional_validators import BeforeValidator -from typing import List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Bill pay (synchronous solution) + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | -class BillLineItemTypedDict(TypedDict): - description: NotRequired[Nullable[str]] - r"""Friendly name of the goods or services received.""" - unit_amount: NotRequired[Decimal] - r"""Unit price of the goods or service.""" - quantity: NotRequired[Decimal] - r"""Number of units of goods or services received.""" - tax_amount: NotRequired[Decimal] - r"""Amount of tax applied to the line item.""" - account_ref: NotRequired[BillAccountRefTypedDict] - r"""Reference to the account to which the line item is linked.""" - total_amount: NotRequired[Nullable[Decimal]] - r"""Total amount of the line, including tax.""" - tax_rate_ref: NotRequired[BillTaxRateRefTypedDict] - r"""Reference to the tax rate to which the line item is linked.""" - tracking_refs: NotRequired[Nullable[List[TrackingRefTypedDict]]] + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 +from __future__ import annotations +from decimal import Decimal +from codat_sync_for_payables.utils.serializers import serialize_decimal, validate_decimal +import pprint +import re # noqa: F401 +import json + +from pydantic import BeforeValidator, PlainSerializer, BaseModel, ConfigDict, Field, model_serializer +from typing import Annotated, Any, ClassVar, Dict, List, Optional, Union +from codat_sync_for_payables.models.shared.billaccountref import BillAccountRef, BillAccountRefTypedDict +from codat_sync_for_payables.models.shared.billtaxrateref import BillTaxRateRef, BillTaxRateRefTypedDict +from codat_sync_for_payables.models.shared.trackingref import TrackingRef, TrackingRefTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_sync_for_payables.types import OptionalNullable, UNSET, UNSET_SENTINEL class BillLineItem(BaseModel): - description: OptionalNullable[str] = UNSET - r"""Friendly name of the goods or services received.""" - - unit_amount: Annotated[ - Annotated[ - Optional[Decimal], - BeforeValidator(validate_decimal), - PlainSerializer(serialize_decimal(False)), - ], - pydantic.Field(alias="unitAmount"), - ] = None - r"""Unit price of the goods or service.""" - - quantity: Annotated[ - Optional[Decimal], - BeforeValidator(validate_decimal), - PlainSerializer(serialize_decimal(False)), - ] = None - r"""Number of units of goods or services received.""" - - tax_amount: Annotated[ - Annotated[ - Optional[Decimal], - BeforeValidator(validate_decimal), - PlainSerializer(serialize_decimal(False)), - ], - pydantic.Field(alias="taxAmount"), - ] = None - r"""Amount of tax applied to the line item.""" - - account_ref: Annotated[ - Optional[BillAccountRef], pydantic.Field(alias="accountRef") - ] = None - r"""Reference to the account to which the line item is linked.""" - - total_amount: Annotated[ - Annotated[ - OptionalNullable[Decimal], - BeforeValidator(validate_decimal), - PlainSerializer(serialize_decimal(False)), - ], - pydantic.Field(alias="totalAmount"), - ] = UNSET - r"""Total amount of the line, including tax.""" - - tax_rate_ref: Annotated[ - Optional[BillTaxRateRef], pydantic.Field(alias="taxRateRef") - ] = None - r"""Reference to the tax rate to which the line item is linked.""" - - tracking_refs: Annotated[ - OptionalNullable[List[TrackingRef]], pydantic.Field(alias="trackingRefs") - ] = UNSET @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "description", - "unitAmount", - "quantity", - "taxAmount", - "accountRef", - "totalAmount", - "taxRateRef", - "trackingRefs", - ] - ) - nullable_fields = set(["description", "totalAmount", "trackingRefs"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - BillLineItem.model_rebuild() -except NameError: - pass + _nullable = {'description', 'totalAmount', 'total_amount', 'trackingRefs', 'tracking_refs'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + BillLineItem + """ # noqa: E501 + description: OptionalNullable[str] = Field(default=UNSET, description="Friendly name of the goods or services received.") + unit_amount: Annotated[Optional[Decimal], BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(default=None, description="Unit price of the goods or service.", alias="unitAmount") + quantity: Annotated[Optional[Decimal], BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(default=None, description="Number of units of goods or services received.") + tax_amount: Annotated[Optional[Decimal], BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(default=None, description="Amount of tax applied to the line item.", alias="taxAmount") + account_ref: Optional[BillAccountRef] = Field(default=None, alias="accountRef") + total_amount: Annotated[OptionalNullable[Decimal], BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(default=UNSET, description="Total amount of the line, including tax.", alias="totalAmount") + tax_rate_ref: Optional[BillTaxRateRef] = Field(default=None, alias="taxRateRef") + tracking_refs: OptionalNullable[List[TrackingRef]] = Field(default=UNSET, alias="trackingRefs") + __properties: ClassVar[List[str]] = ["description", "unitAmount", "quantity", "taxAmount", "accountRef", "totalAmount", "taxRateRef", "trackingRefs"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of BillLineItem from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of account_ref + if self.account_ref: + _dict['accountRef'] = self.account_ref.to_dict() + # override the default output from pydantic by calling `to_dict()` of tax_rate_ref + if self.tax_rate_ref: + _dict['taxRateRef'] = self.tax_rate_ref.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in tracking_refs (list) + _items = [] + if self.tracking_refs: + for _item_tracking_refs in self.tracking_refs: + if _item_tracking_refs: + _items.append(_item_tracking_refs.to_dict()) + _dict['trackingRefs'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of BillLineItem from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "description": obj.get("description"), + "unitAmount": obj.get("unitAmount"), + "quantity": obj.get("quantity"), + "taxAmount": obj.get("taxAmount"), + "accountRef": BillAccountRef.from_dict(obj["accountRef"]) if obj.get("accountRef") is not None else None, + "totalAmount": obj.get("totalAmount"), + "taxRateRef": BillTaxRateRef.from_dict(obj["taxRateRef"]) if obj.get("taxRateRef") is not None else None, + "trackingRefs": [TrackingRef.from_dict(_item) for _item in obj["trackingRefs"]] if obj.get("trackingRefs") is not None else None + }) + return _obj + + + + + +class BillLineItemTypedDict(TypedDict): + """TypedDict variant of BillLineItem, for dict-literal request/response inputs.""" + description: NotRequired[Optional[str]] + unit_amount: NotRequired[Optional[Decimal]] + quantity: NotRequired[Optional[Decimal]] + tax_amount: NotRequired[Optional[Decimal]] + account_ref: NotRequired[Optional[BillAccountRefTypedDict]] + total_amount: NotRequired[Optional[Decimal]] + tax_rate_ref: NotRequired[Optional[BillTaxRateRefTypedDict]] + tracking_refs: NotRequired[Optional[List[TrackingRefTypedDict]]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/billmappingoptions.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/billmappingoptions.py index e63d8752d..6d384d3ac 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/billmappingoptions.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/billmappingoptions.py @@ -1,53 +1,126 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .accountmappingoption import AccountMappingOption, AccountMappingOptionTypedDict -from .pagination import Pagination, PaginationTypedDict -from .taxratemappingoption import TaxRateMappingOption, TaxRateMappingOptionTypedDict -from codat_sync_for_payables.types import BaseModel, Nullable, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Bill pay (synchronous solution) + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | -class BillMappingOptionsTypedDict(TypedDict): - r"""The bill mapping options for a company's accounting software.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 - accounts: NotRequired[List[Nullable[AccountMappingOptionTypedDict]]] - tax_rates: NotRequired[List[TaxRateMappingOptionTypedDict]] - pagination: NotRequired[PaginationTypedDict] +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_sync_for_payables.models.shared.accountmappingoption import AccountMappingOption, AccountMappingOptionTypedDict +from codat_sync_for_payables.models.shared.pagination import Pagination, PaginationTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict +from codat_sync_for_payables.models.shared.taxratemappingoption import TaxRateMappingOption, TaxRateMappingOptionTypedDict +from codat_sync_for_payables.types import Nullable class BillMappingOptions(BaseModel): - r"""The bill mapping options for a company's accounting software.""" + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + The bill mapping options for a company's accounting software. + """ # noqa: E501 accounts: Optional[List[Nullable[AccountMappingOption]]] = None + tax_rates: Optional[List[TaxRateMappingOption]] = Field(default=None, alias="taxRates") + pagination: Optional[Pagination] = None + __properties: ClassVar[List[str]] = ["accounts", "taxRates", "pagination"] - tax_rates: Annotated[ - Optional[List[TaxRateMappingOption]], pydantic.Field(alias="taxRates") - ] = None + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) - pagination: Optional[Pagination] = None - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["accounts", "taxRates", "pagination"]) - serialized = handler(self) - m = {} + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of BillMappingOptions from a JSON string""" + return cls.from_dict(json.loads(json_str)) - return m + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: -try: - BillMappingOptions.model_rebuild() -except NameError: - pass + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in accounts (list) + _items = [] + if self.accounts: + for _item_accounts in self.accounts: + if _item_accounts: + _items.append(_item_accounts.to_dict()) + _dict['accounts'] = _items + # override the default output from pydantic by calling `to_dict()` of pagination + if self.pagination: + _dict['pagination'] = self.pagination.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in tax_rates (list) + _items = [] + if self.tax_rates: + for _item_tax_rates in self.tax_rates: + if _item_tax_rates: + _items.append(_item_tax_rates.to_dict()) + _dict['taxRates'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of BillMappingOptions from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "accounts": [AccountMappingOption.from_dict(_item) for _item in obj["accounts"]] if obj.get("accounts") is not None else None, + "taxRates": [TaxRateMappingOption.from_dict(_item) for _item in obj["taxRates"]] if obj.get("taxRates") is not None else None, + "pagination": Pagination.from_dict(obj["pagination"]) if obj.get("pagination") is not None else None + }) + return _obj + + + + + +class BillMappingOptionsTypedDict(TypedDict): + """TypedDict variant of BillMappingOptions, for dict-literal request/response inputs.""" + accounts: NotRequired[Optional[List[Nullable[AccountMappingOptionTypedDict]]]] + tax_rates: NotRequired[Optional[List[TaxRateMappingOptionTypedDict]]] + pagination: NotRequired[Optional[PaginationTypedDict]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/billpayment.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/billpayment.py index 30fe531e8..5fc502a8c 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/billpayment.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/billpayment.py @@ -1,162 +1,125 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .billpaymentaccountref import BillPaymentAccountRef, BillPaymentAccountRefTypedDict -from codat_sync_for_payables.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from codat_sync_for_payables.utils import serialize_decimal, validate_decimal -from decimal import Decimal -import pydantic -from pydantic import model_serializer -from pydantic.functional_serializers import PlainSerializer -from pydantic.functional_validators import BeforeValidator -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class BillPaymentTypedDict(TypedDict): - id: NotRequired[str] - r"""Identifier for the bill payment, unique for the company in the accounting software.""" - amount: NotRequired[Decimal] - r"""Amount of the payment in the bill currency.""" - date_: NotRequired[str] - reference: NotRequired[Nullable[str]] - r"""Additional information associated with the payment.""" - account_ref: NotRequired[BillPaymentAccountRefTypedDict] - r"""Reference to the bank account / credit card which you are using to pay the bill.""" - currency_rate: NotRequired[Nullable[Decimal]] - r"""Rate to convert the total amount of the payment into the base currency for the company at the time of the payment. - - Currency rates in Codat are implemented as the multiple of foreign currency units to each base currency unit. - - It is not possible to perform the currency conversion with two or more non-base currencies participating in the transaction. For example, if a company's base currency is USD, and it has a bill issued in EUR, then the bill payment must happen in USD or EUR. - - Where the currency rate is provided by the underlying accounting software, it will be available from Codat with the same precision (up to a maximum of 9 decimal places). - - For accounting software which do not provide an explicit currency rate, it is calculated as `baseCurrency / foreignCurrency` and will be returned to 9 decimal places. +""" + Bill pay (synchronous solution) - ## Examples with base currency of GBP + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | - | Foreign Currency | Foreign Amount | Currency Rate | Base Currency Amount (GBP) | - | :--------------- | :------------- | :------------ | :------------------------- | - | **USD** | $20 | 0.781 | £15.62 | - | **EUR** | €20 | 0.885 | £17.70 | - | **RUB** | ₽20 | 0.011 | £0.22 | + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - ## Examples with base currency of USD - - | Foreign Currency | Foreign Amount | Currency Rate | Base Currency Amount (USD) | - | :--------------- | :------------- | :------------ | :------------------------- | - | **GBP** | £20 | 1.277 | $25.54 | - | **EUR** | €20 | 1.134 | $22.68 | - | **RUB** | ₽20 | 0.015 | $0.30 | - - - ### Integration-specific details - - | Integration | Scenario | System behavior | - |-------------------|-------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| - | QuickBooks Online | Transaction currency differs from base currency | If currency rate value is left `null`, a rate of 1 will be used by QBO by default. To override this, specify a currencyRate in the request body. | - """ + Do not edit the class manually. +""" # noqa: E501 +from __future__ import annotations +from decimal import Decimal +from codat_sync_for_payables.utils.serializers import serialize_decimal, validate_decimal +import pprint +import re # noqa: F401 +import json + +from pydantic import BeforeValidator, PlainSerializer, BaseModel, ConfigDict, Field, model_serializer +from typing import Annotated, Any, ClassVar, Dict, List, Optional, Union +from codat_sync_for_payables.models.shared.billpaymentaccountref import BillPaymentAccountRef, BillPaymentAccountRefTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_sync_for_payables.types import OptionalNullable, UNSET, UNSET_SENTINEL class BillPayment(BaseModel): - id: Optional[str] = None - r"""Identifier for the bill payment, unique for the company in the accounting software.""" - - amount: Annotated[ - Optional[Decimal], - BeforeValidator(validate_decimal), - PlainSerializer(serialize_decimal(False)), - ] = None - r"""Amount of the payment in the bill currency.""" - date_: Annotated[Optional[str], pydantic.Field(alias="date")] = None - - reference: OptionalNullable[str] = UNSET - r"""Additional information associated with the payment.""" - - account_ref: Annotated[ - Optional[BillPaymentAccountRef], pydantic.Field(alias="accountRef") - ] = None - r"""Reference to the bank account / credit card which you are using to pay the bill.""" - - currency_rate: Annotated[ - Annotated[ - OptionalNullable[Decimal], - BeforeValidator(validate_decimal), - PlainSerializer(serialize_decimal(False)), - ], - pydantic.Field(alias="currencyRate"), - ] = UNSET - r"""Rate to convert the total amount of the payment into the base currency for the company at the time of the payment. - - Currency rates in Codat are implemented as the multiple of foreign currency units to each base currency unit. - - It is not possible to perform the currency conversion with two or more non-base currencies participating in the transaction. For example, if a company's base currency is USD, and it has a bill issued in EUR, then the bill payment must happen in USD or EUR. - - Where the currency rate is provided by the underlying accounting software, it will be available from Codat with the same precision (up to a maximum of 9 decimal places). - - For accounting software which do not provide an explicit currency rate, it is calculated as `baseCurrency / foreignCurrency` and will be returned to 9 decimal places. + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'currencyRate', 'currency_rate', 'reference'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Identifier for the bill payment, unique for the company in the accounting software.") + amount: Annotated[Optional[Decimal], BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(default=None, description="Amount of the payment in the bill currency.") + date_: Optional[str] = Field(default=None, description="Date the bill payment was recorded in the accounting software.", alias="date") + reference: OptionalNullable[str] = Field(default=UNSET, description="Additional information associated with the payment.") + account_ref: Optional[BillPaymentAccountRef] = Field(default=None, alias="accountRef") + currency_rate: Annotated[OptionalNullable[Decimal], BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(default=UNSET, description="Rate to convert the total amount of the payment into the base currency for the company at the time of the payment. Currency rates in Codat are implemented as the multiple of foreign currency units to each base currency unit. It is not possible to perform the currency conversion with two or more non-base currencies participating in the transaction. For example, if a company's base currency is USD, and it has a bill issued in EUR, then the bill payment must happen in USD or EUR. Where the currency rate is provided by the underlying accounting software, it will be available from Codat with the same precision (up to a maximum of 9 decimal places). For accounting software which do not provide an explicit currency rate, it is calculated as `baseCurrency / foreignCurrency` and will be returned to 9 decimal places. ## Examples with base currency of GBP | Foreign Currency | Foreign Amount | Currency Rate | Base Currency Amount (GBP) | | :--------------- | :------------- | :------------ | :------------------------- | | **USD** | $20 | 0.781 | £15.62 | | **EUR** | €20 | 0.885 | £17.70 | | **RUB** | ₽20 | 0.011 | £0.22 | ## Examples with base currency of USD | Foreign Currency | Foreign Amount | Currency Rate | Base Currency Amount (USD) | | :--------------- | :------------- | :------------ | :------------------------- | | **GBP** | £20 | 1.277 | $25.54 | | **EUR** | €20 | 1.134 | $22.68 | | **RUB** | ₽20 | 0.015 | $0.30 | ### Integration-specific details | Integration | Scenario | System behavior | |-------------------|-------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| | QuickBooks Online | Transaction currency differs from base currency | If currency rate value is left `null`, a rate of 1 will be used by QBO by default. To override this, specify a currencyRate in the request body. |", alias="currencyRate") + __properties: ClassVar[List[str]] = ["id", "amount", "date", "reference", "accountRef", "currencyRate"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of BillPayment from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of account_ref + if self.account_ref: + _dict['accountRef'] = self.account_ref.to_dict() + return _dict - ## Examples with base currency of GBP + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of BillPayment from a dict""" + if obj is None: + return None - | Foreign Currency | Foreign Amount | Currency Rate | Base Currency Amount (GBP) | - | :--------------- | :------------- | :------------ | :------------------------- | - | **USD** | $20 | 0.781 | £15.62 | - | **EUR** | €20 | 0.885 | £17.70 | - | **RUB** | ₽20 | 0.011 | £0.22 | + if not isinstance(obj, dict): + return cls.model_validate(obj) - ## Examples with base currency of USD + _obj = cls.model_validate({ + "id": obj.get("id"), + "amount": obj.get("amount"), + "date": obj.get("date"), + "reference": obj.get("reference"), + "accountRef": BillPaymentAccountRef.from_dict(obj["accountRef"]) if obj.get("accountRef") is not None else None, + "currencyRate": obj.get("currencyRate") + }) + return _obj - | Foreign Currency | Foreign Amount | Currency Rate | Base Currency Amount (USD) | - | :--------------- | :------------- | :------------ | :------------------------- | - | **GBP** | £20 | 1.277 | $25.54 | - | **EUR** | €20 | 1.134 | $22.68 | - | **RUB** | ₽20 | 0.015 | $0.30 | - ### Integration-specific details - | Integration | Scenario | System behavior | - |-------------------|-------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| - | QuickBooks Online | Transaction currency differs from base currency | If currency rate value is left `null`, a rate of 1 will be used by QBO by default. To override this, specify a currencyRate in the request body. | - """ - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - ["id", "amount", "date", "reference", "accountRef", "currencyRate"] - ) - nullable_fields = set(["reference", "currencyRate"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - BillPayment.model_rebuild() -except NameError: - pass +class BillPaymentTypedDict(TypedDict): + """TypedDict variant of BillPayment, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + amount: NotRequired[Optional[Decimal]] + date_: NotRequired[Optional[str]] + reference: NotRequired[Optional[str]] + account_ref: NotRequired[Optional[BillPaymentAccountRefTypedDict]] + currency_rate: NotRequired[Optional[Decimal]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/billpaymentaccountref.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/billpaymentaccountref.py index 1f0115564..e068a7531 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/billpaymentaccountref.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/billpaymentaccountref.py @@ -1,19 +1,99 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_payables.types import BaseModel -from typing_extensions import TypedDict +""" + Bill pay (synchronous solution) + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | -class BillPaymentAccountRefTypedDict(TypedDict): - r"""Reference to the bank account / credit card which you are using to pay the bill.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 - id: str - r"""Unique ID of the bank account / credit card""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict class BillPaymentAccountRef(BaseModel): - r"""Reference to the bank account / credit card which you are using to pay the bill.""" - id: str - r"""Unique ID of the bank account / credit card""" + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + Reference to the bank account / credit card which you are using to pay the bill. + """ # noqa: E501 + id: str = Field(description="Unique ID of the bank account / credit card") + __properties: ClassVar[List[str]] = ["id"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of BillPaymentAccountRef from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of BillPaymentAccountRef from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id") + }) + return _obj + + + + + +class BillPaymentAccountRefTypedDict(TypedDict): + """TypedDict variant of BillPaymentAccountRef, for dict-literal request/response inputs.""" + id: NotRequired[str] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/billpaymentprototype.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/billpaymentprototype.py index 2f8315c02..e96a7f73f 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/billpaymentprototype.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/billpaymentprototype.py @@ -1,152 +1,122 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .billpaymentaccountref import BillPaymentAccountRef, BillPaymentAccountRefTypedDict -from codat_sync_for_payables.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from codat_sync_for_payables.utils import serialize_decimal, validate_decimal -from decimal import Decimal -import pydantic -from pydantic import model_serializer -from pydantic.functional_serializers import PlainSerializer -from pydantic.functional_validators import BeforeValidator -from typing_extensions import Annotated, NotRequired, TypedDict - - -class BillPaymentPrototypeTypedDict(TypedDict): - amount: Decimal - r"""Amount of the payment in the bill currency.""" - date_: str - account_ref: BillPaymentAccountRefTypedDict - r"""Reference to the bank account / credit card which you are using to pay the bill.""" - reference: NotRequired[Nullable[str]] - r"""Additional information associated with the payment.""" - currency_rate: NotRequired[Nullable[Decimal]] - r"""Rate to convert the total amount of the payment into the base currency for the company at the time of the payment. - - Currency rates in Codat are implemented as the multiple of foreign currency units to each base currency unit. - - It is not possible to perform the currency conversion with two or more non-base currencies participating in the transaction. For example, if a company's base currency is USD, and it has a bill issued in EUR, then the bill payment must happen in USD or EUR. - - Where the currency rate is provided by the underlying accounting software, it will be available from Codat with the same precision (up to a maximum of 9 decimal places). - - For accounting software which do not provide an explicit currency rate, it is calculated as `baseCurrency / foreignCurrency` and will be returned to 9 decimal places. +""" + Bill pay (synchronous solution) - ## Examples with base currency of GBP + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | - | Foreign Currency | Foreign Amount | Currency Rate | Base Currency Amount (GBP) | - | :--------------- | :------------- | :------------ | :------------------------- | - | **USD** | $20 | 0.781 | £15.62 | - | **EUR** | €20 | 0.885 | £17.70 | - | **RUB** | ₽20 | 0.011 | £0.22 | + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - ## Examples with base currency of USD - - | Foreign Currency | Foreign Amount | Currency Rate | Base Currency Amount (USD) | - | :--------------- | :------------- | :------------ | :------------------------- | - | **GBP** | £20 | 1.277 | $25.54 | - | **EUR** | €20 | 1.134 | $22.68 | - | **RUB** | ₽20 | 0.015 | $0.30 | - - - ### Integration-specific details - - | Integration | Scenario | System behavior | - |-------------------|-------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| - | QuickBooks Online | Transaction currency differs from base currency | If currency rate value is left `null`, a rate of 1 will be used by QBO by default. To override this, specify a currencyRate in the request body. | - """ + Do not edit the class manually. +""" # noqa: E501 +from __future__ import annotations +from decimal import Decimal +from codat_sync_for_payables.utils.serializers import serialize_decimal, validate_decimal +import pprint +import re # noqa: F401 +import json + +from pydantic import BeforeValidator, PlainSerializer, BaseModel, ConfigDict, Field, model_serializer +from typing import Annotated, Any, ClassVar, Dict, List, Optional, Union +from codat_sync_for_payables.models.shared.billpaymentaccountref import BillPaymentAccountRef, BillPaymentAccountRefTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_sync_for_payables.types import OptionalNullable, UNSET, UNSET_SENTINEL class BillPaymentPrototype(BaseModel): - amount: Annotated[ - Decimal, - BeforeValidator(validate_decimal), - PlainSerializer(serialize_decimal(False)), - ] - r"""Amount of the payment in the bill currency.""" - - date_: Annotated[str, pydantic.Field(alias="date")] - account_ref: Annotated[BillPaymentAccountRef, pydantic.Field(alias="accountRef")] - r"""Reference to the bank account / credit card which you are using to pay the bill.""" - - reference: OptionalNullable[str] = UNSET - r"""Additional information associated with the payment.""" - - currency_rate: Annotated[ - Annotated[ - OptionalNullable[Decimal], - BeforeValidator(validate_decimal), - PlainSerializer(serialize_decimal(False)), - ], - pydantic.Field(alias="currencyRate"), - ] = UNSET - r"""Rate to convert the total amount of the payment into the base currency for the company at the time of the payment. - - Currency rates in Codat are implemented as the multiple of foreign currency units to each base currency unit. - - It is not possible to perform the currency conversion with two or more non-base currencies participating in the transaction. For example, if a company's base currency is USD, and it has a bill issued in EUR, then the bill payment must happen in USD or EUR. - - Where the currency rate is provided by the underlying accounting software, it will be available from Codat with the same precision (up to a maximum of 9 decimal places). - - For accounting software which do not provide an explicit currency rate, it is calculated as `baseCurrency / foreignCurrency` and will be returned to 9 decimal places. - - ## Examples with base currency of GBP - - | Foreign Currency | Foreign Amount | Currency Rate | Base Currency Amount (GBP) | - | :--------------- | :------------- | :------------ | :------------------------- | - | **USD** | $20 | 0.781 | £15.62 | - | **EUR** | €20 | 0.885 | £17.70 | - | **RUB** | ₽20 | 0.011 | £0.22 | - - ## Examples with base currency of USD + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'currencyRate', 'currency_rate', 'reference'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + BillPaymentPrototype + """ # noqa: E501 + amount: Annotated[Decimal, BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(description="Amount of the payment in the bill currency.") + date_: str = Field(description="Date the bill payment was recorded in the accounting software.", alias="date") + reference: OptionalNullable[str] = Field(default=UNSET, description="Additional information associated with the payment.") + account_ref: BillPaymentAccountRef = Field(alias="accountRef") + currency_rate: Annotated[OptionalNullable[Decimal], BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(default=UNSET, description="Rate to convert the total amount of the payment into the base currency for the company at the time of the payment. Currency rates in Codat are implemented as the multiple of foreign currency units to each base currency unit. It is not possible to perform the currency conversion with two or more non-base currencies participating in the transaction. For example, if a company's base currency is USD, and it has a bill issued in EUR, then the bill payment must happen in USD or EUR. Where the currency rate is provided by the underlying accounting software, it will be available from Codat with the same precision (up to a maximum of 9 decimal places). For accounting software which do not provide an explicit currency rate, it is calculated as `baseCurrency / foreignCurrency` and will be returned to 9 decimal places. ## Examples with base currency of GBP | Foreign Currency | Foreign Amount | Currency Rate | Base Currency Amount (GBP) | | :--------------- | :------------- | :------------ | :------------------------- | | **USD** | $20 | 0.781 | £15.62 | | **EUR** | €20 | 0.885 | £17.70 | | **RUB** | ₽20 | 0.011 | £0.22 | ## Examples with base currency of USD | Foreign Currency | Foreign Amount | Currency Rate | Base Currency Amount (USD) | | :--------------- | :------------- | :------------ | :------------------------- | | **GBP** | £20 | 1.277 | $25.54 | | **EUR** | €20 | 1.134 | $22.68 | | **RUB** | ₽20 | 0.015 | $0.30 | ### Integration-specific details | Integration | Scenario | System behavior | |-------------------|-------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| | QuickBooks Online | Transaction currency differs from base currency | If currency rate value is left `null`, a rate of 1 will be used by QBO by default. To override this, specify a currencyRate in the request body. |", alias="currencyRate") + __properties: ClassVar[List[str]] = ["amount", "date", "reference", "accountRef", "currencyRate"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of BillPaymentPrototype from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of account_ref + if self.account_ref: + _dict['accountRef'] = self.account_ref.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of BillPaymentPrototype from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "amount": obj.get("amount"), + "date": obj.get("date"), + "reference": obj.get("reference"), + "accountRef": BillPaymentAccountRef.from_dict(obj["accountRef"]) if obj.get("accountRef") is not None else None, + "currencyRate": obj.get("currencyRate") + }) + return _obj - | Foreign Currency | Foreign Amount | Currency Rate | Base Currency Amount (USD) | - | :--------------- | :------------- | :------------ | :------------------------- | - | **GBP** | £20 | 1.277 | $25.54 | - | **EUR** | €20 | 1.134 | $22.68 | - | **RUB** | ₽20 | 0.015 | $0.30 | - ### Integration-specific details - | Integration | Scenario | System behavior | - |-------------------|-------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| - | QuickBooks Online | Transaction currency differs from base currency | If currency rate value is left `null`, a rate of 1 will be used by QBO by default. To override this, specify a currencyRate in the request body. | - """ - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["reference", "currencyRate"]) - nullable_fields = set(["reference", "currencyRate"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - BillPaymentPrototype.model_rebuild() -except NameError: - pass +class BillPaymentPrototypeTypedDict(TypedDict): + """TypedDict variant of BillPaymentPrototype, for dict-literal request/response inputs.""" + amount: NotRequired[Decimal] + date_: NotRequired[str] + reference: NotRequired[Optional[str]] + account_ref: NotRequired[BillPaymentAccountRefTypedDict] + currency_rate: NotRequired[Optional[Decimal]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/billprototype.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/billprototype.py index 643426e88..63377700a 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/billprototype.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/billprototype.py @@ -1,180 +1,140 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .billlineitem import BillLineItem, BillLineItemTypedDict -from .billstatus import BillStatus -from .supplierref import SupplierRef, SupplierRefTypedDict -from codat_sync_for_payables.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from codat_sync_for_payables.utils import serialize_decimal, validate_decimal -from decimal import Decimal -import pydantic -from pydantic import model_serializer -from pydantic.functional_serializers import PlainSerializer -from pydantic.functional_validators import BeforeValidator -from typing import List -from typing_extensions import Annotated, NotRequired, TypedDict - - -class BillPrototypeTypedDict(TypedDict): - supplier_ref: SupplierRefTypedDict - r"""Reference to the supplier the record relates to.""" - issue_date: str - due_date: str - currency: str - r"""The currency data type in Codat is the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code, e.g. _GBP_. - - ## Unknown currencies - - In line with the ISO 4217 specification, the code _XXX_ is used when the data source does not return a currency for a transaction. - - There are only a very small number of edge cases where this currency code is returned by the Codat system. - """ - status: BillStatus - r"""Current state of the bill. If creating a bill the status must be `Open`.""" - reference: NotRequired[Nullable[str]] - r"""User-friendly reference for the bill.""" - currency_rate: NotRequired[Nullable[Decimal]] - r"""Rate to convert the total amount of the payment into the base currency for the company at the time of the payment. - - Currency rates in Codat are implemented as the multiple of foreign currency units to each base currency unit. +""" + Bill pay (synchronous solution) - It is not possible to perform the currency conversion with two or more non-base currencies participating in the transaction. For example, if a company's base currency is USD, and it has a bill issued in EUR, then the bill payment must happen in USD or EUR. + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | - Where the currency rate is provided by the underlying accounting software, it will be available from Codat with the same precision (up to a maximum of 9 decimal places). + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - For accounting software which do not provide an explicit currency rate, it is calculated as `baseCurrency / foreignCurrency` and will be returned to 9 decimal places. - - ## Examples with base currency of GBP - - | Foreign Currency | Foreign Amount | Currency Rate | Base Currency Amount (GBP) | - | :--------------- | :------------- | :------------ | :------------------------- | - | **USD** | $20 | 0.781 | £15.62 | - | **EUR** | €20 | 0.885 | £17.70 | - | **RUB** | ₽20 | 0.011 | £0.22 | - - ## Examples with base currency of USD - - | Foreign Currency | Foreign Amount | Currency Rate | Base Currency Amount (USD) | - | :--------------- | :------------- | :------------ | :------------------------- | - | **GBP** | £20 | 1.277 | $25.54 | - | **EUR** | €20 | 1.134 | $22.68 | - | **RUB** | ₽20 | 0.015 | $0.30 | - - - ### Integration-specific details - - | Integration | Scenario | System behavior | - |-------------------|-------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| - | QuickBooks Online | Transaction currency differs from base currency | If currency rate value is left `null`, a rate of 1 will be used by QBO by default. To override this, specify a currencyRate in the request body. | - """ - line_items: NotRequired[Nullable[List[BillLineItemTypedDict]]] - r"""Array of Bill line items.""" + Do not edit the class manually. +""" # noqa: E501 +from __future__ import annotations +from decimal import Decimal +from codat_sync_for_payables.utils.serializers import serialize_decimal, validate_decimal +import pprint +import re # noqa: F401 +import json + +from pydantic import BeforeValidator, PlainSerializer, BaseModel, ConfigDict, Field, model_serializer +from typing import Annotated, Any, ClassVar, Dict, List, Optional, Union +from codat_sync_for_payables.models.shared.billlineitem import BillLineItem, BillLineItemTypedDict +from codat_sync_for_payables.models.shared.billstatus import BillStatus +from codat_sync_for_payables.models.shared.supplierref import SupplierRef, SupplierRefTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_sync_for_payables.types import OptionalNullable, UNSET, UNSET_SENTINEL class BillPrototype(BaseModel): - supplier_ref: Annotated[SupplierRef, pydantic.Field(alias="supplierRef")] - r"""Reference to the supplier the record relates to.""" - - issue_date: Annotated[str, pydantic.Field(alias="issueDate")] - due_date: Annotated[str, pydantic.Field(alias="dueDate")] - - currency: str - r"""The currency data type in Codat is the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code, e.g. _GBP_. - - ## Unknown currencies - - In line with the ISO 4217 specification, the code _XXX_ is used when the data source does not return a currency for a transaction. - - There are only a very small number of edge cases where this currency code is returned by the Codat system. + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'currencyRate', 'currency_rate', 'lineItems', 'line_items', 'reference'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } """ - + BillPrototype + """ # noqa: E501 + reference: OptionalNullable[str] = Field(default=UNSET, description="Additional information associated with the payment.") + supplier_ref: SupplierRef = Field(alias="supplierRef") + issue_date: str = Field(description="Date of the bill as recorded in the accounting software.", alias="issueDate") + due_date: str = Field(description="Date the supplier is due to be paid.", alias="dueDate") + currency: str = Field(description="The currency data type in Codat is the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code, e.g. _GBP_. ## Unknown currencies In line with the ISO 4217 specification, the code _XXX_ is used when the data source does not return a currency for a transaction. There are only a very small number of edge cases where this currency code is returned by the Codat system.") + currency_rate: Annotated[OptionalNullable[Decimal], BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(default=UNSET, description="Rate to convert the total amount of the payment into the base currency for the company at the time of the payment. Currency rates in Codat are implemented as the multiple of foreign currency units to each base currency unit. It is not possible to perform the currency conversion with two or more non-base currencies participating in the transaction. For example, if a company's base currency is USD, and it has a bill issued in EUR, then the bill payment must happen in USD or EUR. Where the currency rate is provided by the underlying accounting software, it will be available from Codat with the same precision (up to a maximum of 9 decimal places). For accounting software which do not provide an explicit currency rate, it is calculated as `baseCurrency / foreignCurrency` and will be returned to 9 decimal places. ## Examples with base currency of GBP | Foreign Currency | Foreign Amount | Currency Rate | Base Currency Amount (GBP) | | :--------------- | :------------- | :------------ | :------------------------- | | **USD** | $20 | 0.781 | £15.62 | | **EUR** | €20 | 0.885 | £17.70 | | **RUB** | ₽20 | 0.011 | £0.22 | ## Examples with base currency of USD | Foreign Currency | Foreign Amount | Currency Rate | Base Currency Amount (USD) | | :--------------- | :------------- | :------------ | :------------------------- | | **GBP** | £20 | 1.277 | $25.54 | | **EUR** | €20 | 1.134 | $22.68 | | **RUB** | ₽20 | 0.015 | $0.30 | ### Integration-specific details | Integration | Scenario | System behavior | |-------------------|-------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| | QuickBooks Online | Transaction currency differs from base currency | If currency rate value is left `null`, a rate of 1 will be used by QBO by default. To override this, specify a currencyRate in the request body. |", alias="currencyRate") + line_items: OptionalNullable[List[BillLineItem]] = Field(default=UNSET, description="Array of Bill line items.", alias="lineItems") status: BillStatus - r"""Current state of the bill. If creating a bill the status must be `Open`.""" - - reference: OptionalNullable[str] = UNSET - r"""User-friendly reference for the bill.""" - - currency_rate: Annotated[ - Annotated[ - OptionalNullable[Decimal], - BeforeValidator(validate_decimal), - PlainSerializer(serialize_decimal(False)), - ], - pydantic.Field(alias="currencyRate"), - ] = UNSET - r"""Rate to convert the total amount of the payment into the base currency for the company at the time of the payment. - - Currency rates in Codat are implemented as the multiple of foreign currency units to each base currency unit. - - It is not possible to perform the currency conversion with two or more non-base currencies participating in the transaction. For example, if a company's base currency is USD, and it has a bill issued in EUR, then the bill payment must happen in USD or EUR. + __properties: ClassVar[List[str]] = ["reference", "supplierRef", "issueDate", "dueDate", "currency", "currencyRate", "lineItems", "status"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of BillPrototype from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of supplier_ref + if self.supplier_ref: + _dict['supplierRef'] = self.supplier_ref.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in line_items (list) + _items = [] + if self.line_items: + for _item_line_items in self.line_items: + if _item_line_items: + _items.append(_item_line_items.to_dict()) + _dict['lineItems'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of BillPrototype from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "reference": obj.get("reference"), + "supplierRef": SupplierRef.from_dict(obj["supplierRef"]) if obj.get("supplierRef") is not None else None, + "issueDate": obj.get("issueDate"), + "dueDate": obj.get("dueDate"), + "currency": obj.get("currency"), + "currencyRate": obj.get("currencyRate"), + "lineItems": [BillLineItem.from_dict(_item) for _item in obj["lineItems"]] if obj.get("lineItems") is not None else None, + "status": obj.get("status") + }) + return _obj - Where the currency rate is provided by the underlying accounting software, it will be available from Codat with the same precision (up to a maximum of 9 decimal places). - For accounting software which do not provide an explicit currency rate, it is calculated as `baseCurrency / foreignCurrency` and will be returned to 9 decimal places. - ## Examples with base currency of GBP - | Foreign Currency | Foreign Amount | Currency Rate | Base Currency Amount (GBP) | - | :--------------- | :------------- | :------------ | :------------------------- | - | **USD** | $20 | 0.781 | £15.62 | - | **EUR** | €20 | 0.885 | £17.70 | - | **RUB** | ₽20 | 0.011 | £0.22 | - ## Examples with base currency of USD - - | Foreign Currency | Foreign Amount | Currency Rate | Base Currency Amount (USD) | - | :--------------- | :------------- | :------------ | :------------------------- | - | **GBP** | £20 | 1.277 | $25.54 | - | **EUR** | €20 | 1.134 | $22.68 | - | **RUB** | ₽20 | 0.015 | $0.30 | - - - ### Integration-specific details - - | Integration | Scenario | System behavior | - |-------------------|-------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| - | QuickBooks Online | Transaction currency differs from base currency | If currency rate value is left `null`, a rate of 1 will be used by QBO by default. To override this, specify a currencyRate in the request body. | - """ - - line_items: Annotated[ - OptionalNullable[List[BillLineItem]], pydantic.Field(alias="lineItems") - ] = UNSET - r"""Array of Bill line items.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["reference", "currencyRate", "lineItems"]) - nullable_fields = set(["reference", "currencyRate", "lineItems"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - BillPrototype.model_rebuild() -except NameError: - pass +class BillPrototypeTypedDict(TypedDict): + """TypedDict variant of BillPrototype, for dict-literal request/response inputs.""" + reference: NotRequired[Optional[str]] + supplier_ref: NotRequired[SupplierRefTypedDict] + issue_date: NotRequired[str] + due_date: NotRequired[str] + currency: NotRequired[str] + currency_rate: NotRequired[Optional[Decimal]] + line_items: NotRequired[Optional[List[BillLineItemTypedDict]]] + status: BillStatus diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/bills.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/bills.py index 69a78e9a7..dc6531cb2 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/bills.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/bills.py @@ -1,36 +1,114 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .bill import Bill, BillTypedDict -from .pagination import Pagination, PaginationTypedDict -from codat_sync_for_payables.types import BaseModel, UNSET_SENTINEL -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import NotRequired, TypedDict +""" + Bill pay (synchronous solution) + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | -class BillsTypedDict(TypedDict): - results: NotRequired[List[BillTypedDict]] - pagination: NotRequired[PaginationTypedDict] + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class Bills(BaseModel): - results: Optional[List[Bill]] = None - pagination: Optional[Pagination] = None +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_sync_for_payables.models.shared.bill import Bill, BillTypedDict +from codat_sync_for_payables.models.shared.pagination import Pagination, PaginationTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class Bills(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["results", "pagination"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + Bills + """ # noqa: E501 + results: Optional[List[Bill]] = None + pagination: Optional[Pagination] = None + __properties: ClassVar[List[str]] = ["results", "pagination"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - return m + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Bills from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in results (list) + _items = [] + if self.results: + for _item_results in self.results: + if _item_results: + _items.append(_item_results.to_dict()) + _dict['results'] = _items + # override the default output from pydantic by calling `to_dict()` of pagination + if self.pagination: + _dict['pagination'] = self.pagination.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Bills from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "results": [Bill.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None, + "pagination": Pagination.from_dict(obj["pagination"]) if obj.get("pagination") is not None else None + }) + return _obj + + + + + +class BillsTypedDict(TypedDict): + """TypedDict variant of Bills, for dict-literal request/response inputs.""" + results: NotRequired[Optional[List[BillTypedDict]]] + pagination: NotRequired[Optional[PaginationTypedDict]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/billstatus.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/billstatus.py index fcd1b5e91..43c9b7239 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/billstatus.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/billstatus.py @@ -1,15 +1,42 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations +import json from enum import Enum +from typing_extensions import Self class BillStatus(str, Enum): - r"""Current state of the bill. If creating a bill the status must be `Open`.""" - - UNKNOWN = "Unknown" - OPEN = "Open" - PARTIALLY_PAID = "PartiallyPaid" - PAID = "Paid" - VOID = "Void" - DRAFT = "Draft" + """ + Current state of the bill. If creating a bill the status must be `Open`. + """ + + """ + allowed enum values + """ + UNKNOWN = 'Unknown' + OPEN = 'Open' + PARTIALLY_PAID = 'PartiallyPaid' + PAID = 'Paid' + VOID = 'Void' + DRAFT = 'Draft' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of BillStatus from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/billtaxrateref.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/billtaxrateref.py index 5fc6fd686..609a1e11b 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/billtaxrateref.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/billtaxrateref.py @@ -1,37 +1,99 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_payables.types import BaseModel, UNSET_SENTINEL -from pydantic import model_serializer -from typing import Optional -from typing_extensions import NotRequired, TypedDict +""" + Bill pay (synchronous solution) + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | -class BillTaxRateRefTypedDict(TypedDict): - r"""Reference to the tax rate to which the line item is linked.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - id: NotRequired[str] - r"""Unique identifier for the tax rate in the accounting software.""" + Do not edit the class manually. +""" # noqa: E501 -class BillTaxRateRef(BaseModel): - r"""Reference to the tax rate to which the line item is linked.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict - id: Optional[str] = None - r"""Unique identifier for the tax rate in the accounting software.""" +class BillTaxRateRef(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["id"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + Reference to the tax rate to which the line item is linked. + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Unique identifier for the tax rate in the accounting software.") + __properties: ClassVar[List[str]] = ["id"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of BillTaxRateRef from a JSON string""" + return cls.from_dict(json.loads(json_str)) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - return m + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of BillTaxRateRef from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id") + }) + return _obj + + + + + +class BillTaxRateRefTypedDict(TypedDict): + """TypedDict variant of BillTaxRateRef, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/clientratelimitwebhook.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/clientratelimitwebhook.py new file mode 100644 index 000000000..06dbcd499 --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/clientratelimitwebhook.py @@ -0,0 +1,112 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_sync_for_payables.models.shared.clientratelimitwebhookpayload import ClientRateLimitWebhookPayload, ClientRateLimitWebhookPayloadTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class ClientRateLimitWebhook(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + ClientRateLimitWebhook + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Unique identifier of the event.") + event_type: Optional[str] = Field(default=None, description="The type of event.", alias="eventType") + generated_date: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.", alias="generatedDate") + payload: Optional[ClientRateLimitWebhookPayload] = None + __properties: ClassVar[List[str]] = ["id", "eventType", "generatedDate", "payload"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ClientRateLimitWebhook from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of payload + if self.payload: + _dict['payload'] = self.payload.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ClientRateLimitWebhook from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "eventType": obj.get("eventType"), + "generatedDate": obj.get("generatedDate"), + "payload": ClientRateLimitWebhookPayload.from_dict(obj["payload"]) if obj.get("payload") is not None else None + }) + return _obj + + + + + +class ClientRateLimitWebhookTypedDict(TypedDict): + """TypedDict variant of ClientRateLimitWebhook, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + event_type: NotRequired[Optional[str]] + generated_date: NotRequired[Optional[str]] + payload: NotRequired[Optional[ClientRateLimitWebhookPayloadTypedDict]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/clientratelimitwebhookpayload.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/clientratelimitwebhookpayload.py new file mode 100644 index 000000000..62be75546 --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/clientratelimitwebhookpayload.py @@ -0,0 +1,105 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class ClientRateLimitWebhookPayload(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + ClientRateLimitWebhookPayload + """ # noqa: E501 + daily_quota: Optional[int] = Field(default=None, description="The number of available requests per day.", alias="dailyQuota") + quota_remaining: Optional[int] = Field(default=None, description="Total number of requests remaining for your client.", alias="quotaRemaining") + expiry_date: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.", alias="expiryDate") + __properties: ClassVar[List[str]] = ["dailyQuota", "quotaRemaining", "expiryDate"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ClientRateLimitWebhookPayload from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ClientRateLimitWebhookPayload from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "dailyQuota": obj.get("dailyQuota"), + "quotaRemaining": obj.get("quotaRemaining"), + "expiryDate": obj.get("expiryDate") + }) + return _obj + + + + + +class ClientRateLimitWebhookPayloadTypedDict(TypedDict): + """TypedDict variant of ClientRateLimitWebhookPayload, for dict-literal request/response inputs.""" + daily_quota: NotRequired[Optional[int]] + quota_remaining: NotRequired[Optional[int]] + expiry_date: NotRequired[Optional[str]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/codatfile.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/codatfile.py index 88f981a5a..0adbb4fae 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/codatfile.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/codatfile.py @@ -1,50 +1,33 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 +"""Speakeasy-compat multipart file helper. Not an OAS schema — Speakeasy emits this +to wrap multipart/form-data file uploads (see AttachmentUpload).""" from __future__ import annotations -from codat_sync_for_payables.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_payables.utils import FieldMetadata, MultipartFormMetadata -import io -import pydantic -from pydantic import model_serializer -from typing import IO, Optional, Union -from typing_extensions import Annotated, NotRequired, TypedDict - -class CodatFileTypedDict(TypedDict): - file_name: str - content: Union[bytes, IO[bytes], io.BufferedReader] - content_type: NotRequired[str] +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import IO, Any, Optional, Union +from typing_extensions import NotRequired, TypedDict class CodatFile(BaseModel): - file_name: Annotated[ - str, pydantic.Field(alias="fileName"), FieldMetadata(multipart=True) - ] - - content: Annotated[ - Union[bytes, IO[bytes], io.BufferedReader], - pydantic.Field(alias=""), - FieldMetadata(multipart=MultipartFormMetadata(content=True)), - ] - - content_type: Annotated[ - Optional[str], - pydantic.Field(alias="Content-Type"), - FieldMetadata(multipart=True), - ] = None @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["contentType"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + file_name: str = Field(alias="fileName") + content: Union[bytes, IO[bytes]] + content_type: Optional[str] = Field(default=None, alias="Content-Type") - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + model_config = ConfigDict( + populate_by_name=True, + arbitrary_types_allowed=True, + protected_namespaces=(), + ) - return m + +class CodatFileTypedDict(TypedDict): + file_name: str + content: Union[bytes, Any] + content_type: NotRequired[Optional[str]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/companies.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/companies.py index ab3f3dc38..81f28fde8 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/companies.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/companies.py @@ -1,58 +1,124 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations -from .company import Company, CompanyTypedDict -from .links import Links, LinksTypedDict -from codat_sync_for_payables.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import List, Optional +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional from typing_extensions import Annotated, NotRequired, TypedDict +from codat_sync_for_payables.models.shared.company import Company, CompanyTypedDict +from codat_sync_for_payables.models.shared.links import Links, LinksTypedDict +from typing import Optional, Set +from typing_extensions import Self +class Companies(BaseModel): -class CompaniesTypedDict(TypedDict): - page_number: int - r"""Current page number.""" - page_size: int - r"""Number of items to return in results array.""" - total_results: int - r"""Total number of items.""" - links: LinksTypedDict - results: NotRequired[List[CompanyTypedDict]] + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + Companies + """ # noqa: E501 + page_number: int = Field(description="Current page number.", alias="pageNumber") + page_size: int = Field(description="Number of items to return in results array.", alias="pageSize") + total_results: int = Field(description="Total number of items.", alias="totalResults") + links: Links = Field(alias="_links") + results: Optional[List[Company]] = None + __properties: ClassVar[List[str]] = ["pageNumber", "pageSize", "totalResults", "_links", "results"] + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) -class Companies(BaseModel): - page_number: Annotated[int, pydantic.Field(alias="pageNumber")] - r"""Current page number.""" - page_size: Annotated[int, pydantic.Field(alias="pageSize")] - r"""Number of items to return in results array.""" + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - total_results: Annotated[int, pydantic.Field(alias="totalResults")] - r"""Total number of items.""" + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - links: Annotated[Links, pydantic.Field(alias="_links")] + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Companies from a JSON string""" + return cls.from_dict(json.loads(json_str)) - results: Optional[List[Company]] = None + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["results"]) - serialized = handler(self) - m = {} + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of links + if self.links: + _dict['_links'] = self.links.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in results (list) + _items = [] + if self.results: + for _item_results in self.results: + if _item_results: + _items.append(_item_results.to_dict()) + _dict['results'] = _items + return _dict - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Companies from a dict""" + if obj is None: + return None - return m + if not isinstance(obj, dict): + return cls.model_validate(obj) + _obj = cls.model_validate({ + "pageNumber": obj.get("pageNumber"), + "pageSize": obj.get("pageSize"), + "totalResults": obj.get("totalResults"), + "_links": Links.from_dict(obj["_links"]) if obj.get("_links") is not None else None, + "results": [Company.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None + }) + return _obj -try: - Companies.model_rebuild() -except NameError: - pass + + + + +class CompaniesTypedDict(TypedDict): + """TypedDict variant of Companies, for dict-literal request/response inputs.""" + page_number: NotRequired[int] + page_size: NotRequired[int] + total_results: NotRequired[int] + links: NotRequired[LinksTypedDict] + results: NotRequired[Optional[List[CompanyTypedDict]]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/company.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/company.py index 4636d9637..e488ef9f3 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/company.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/company.py @@ -1,219 +1,157 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .companyreference import CompanyReference, CompanyReferenceTypedDict -from .connection import Connection, ConnectionTypedDict -from codat_sync_for_payables.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing import Dict, List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Bill pay (synchronous solution) + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | -class CompanyTypedDict(TypedDict): - r"""In Codat, a company represents a business sharing access to their data. Each company can have multiple [connections](https://docs.codat.io/sync-for-payables-api#/schemas/Connection) to different data sources such as one connection to [Xero](https://docs.codat.io/integrations/accounting/xero/accounting-xero) for accounting data, two connections to [Plaid](https://docs.codat.io/integrations/banking/plaid/banking-plaid) for two bank accounts and a connection to [Zettle](https://docs.codat.io/integrations/commerce/zettle/commerce-zettle) for POS data. - - Typically each company is one of your customers. - - When you create a company, you can specify a `name` and we will automatically generate a unique `id` for the company. You can also add a `description` to store any additional information about the company. - """ - - id: str - r"""Unique identifier for your SMB in Codat.""" - name: str - r"""The name of the company""" - redirect: str - r"""The `redirect` [Link URL](https://docs.codat.io/auth-flow/authorize-hosted-link) enabling the customer to start their auth flow journey for the company.""" - description: NotRequired[str] - r"""Additional information about the company. This can be used to store foreign IDs, references, etc.""" - last_sync: NotRequired[str] - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` - - - - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - created: NotRequired[str] - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: + Do not edit the class manually. +""" # noqa: E501 - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated, NotRequired, TypedDict +from codat_sync_for_payables.models.shared.companyreference import CompanyReference, CompanyReferenceTypedDict +from codat_sync_for_payables.models.shared.connection import Connection, ConnectionTypedDict +from typing import Optional, Set +from typing_extensions import Self - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - created_by_user_name: NotRequired[Nullable[str]] - r"""Name of user that created the company in Codat.""" - products: NotRequired[List[str]] - r"""An array of products that are currently enabled for the company.""" - tags: NotRequired[Dict[str, str]] - r"""A collection of user-defined key-value pairs that store custom metadata against the company.""" - reference_parent_company: NotRequired[CompanyReferenceTypedDict] - reference_subsidiary_companies: NotRequired[List[CompanyReferenceTypedDict]] - r"""A list of subsidiary companies owned or controlled by this entity. Empty if the company has no children.""" - data_connections: NotRequired[List[ConnectionTypedDict]] - - +from codat_sync_for_payables.types import OptionalNullable, UNSET, UNSET_SENTINEL class Company(BaseModel): - r"""In Codat, a company represents a business sharing access to their data. Each company can have multiple [connections](https://docs.codat.io/sync-for-payables-api#/schemas/Connection) to different data sources such as one connection to [Xero](https://docs.codat.io/integrations/accounting/xero/accounting-xero) for accounting data, two connections to [Plaid](https://docs.codat.io/integrations/banking/plaid/banking-plaid) for two bank accounts and a connection to [Zettle](https://docs.codat.io/integrations/commerce/zettle/commerce-zettle) for POS data. - - Typically each company is one of your customers. - - When you create a company, you can specify a `name` and we will automatically generate a unique `id` for the company. You can also add a `description` to store any additional information about the company. - """ - - id: str - r"""Unique identifier for your SMB in Codat.""" - - name: str - r"""The name of the company""" - redirect: str - r"""The `redirect` [Link URL](https://docs.codat.io/auth-flow/authorize-hosted-link) enabling the customer to start their auth flow journey for the company.""" - - description: Optional[str] = None - r"""Additional information about the company. This can be used to store foreign IDs, references, etc.""" - - last_sync: Annotated[Optional[str], pydantic.Field(alias="lastSync")] = None - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` - - - - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - - created: Optional[str] = None - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` - - - - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'createdByUserName', 'created_by_user_name'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } """ + In Codat, a company represents a business sharing access to their data. Each company can have multiple [connections](https://docs.codat.io/sync-for-payables-api#/schemas/Connection) to different data sources such as one connection to [Xero](https://docs.codat.io/integrations/accounting/xero/accounting-xero) for accounting data, two connections to [Plaid](https://docs.codat.io/integrations/banking/plaid/banking-plaid) for two bank accounts and a connection to [Zettle](https://docs.codat.io/integrations/commerce/zettle/commerce-zettle) for POS data. Typically each company is one of your customers. When you create a company, you can specify a `name` and we will automatically generate a unique `id` for the company. You can also add a `description` to store any additional information about the company. + """ # noqa: E501 + id: str = Field(description="Unique identifier for your SMB in Codat.") + name: str = Field(description="The name of the company") + description: Optional[str] = Field(default=None, description="Additional information about the company. This can be used to store foreign IDs, references, etc.") + redirect: str = Field(description="The `redirect` [Link URL](https://docs.codat.io/auth-flow/authorize-hosted-link) enabling the customer to start their auth flow journey for the company.") + last_sync: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.", alias="lastSync") + created: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.") + created_by_user_name: OptionalNullable[str] = Field(default=UNSET, description="Name of user that created the company in Codat.", alias="createdByUserName") + products: Optional[List[str]] = Field(default=None, description="An array of products that are currently enabled for the company.") + tags: Optional[Dict[str, str]] = Field(default=None, description="A collection of user-defined key-value pairs that store custom metadata against the company.") + reference_parent_company: Optional[CompanyReference] = Field(default=None, description="The parent entity or controlling organization of this company. Null if the company has no parent.", alias="referenceParentCompany") + reference_subsidiary_companies: Optional[List[CompanyReference]] = Field(default=None, description="A list of subsidiary companies owned or controlled by this entity. Empty if the company has no children.", alias="referenceSubsidiaryCompanies") + data_connections: Optional[List[Connection]] = Field(default=None, alias="dataConnections") + __properties: ClassVar[List[str]] = ["id", "name", "description", "redirect", "lastSync", "created", "createdByUserName", "products", "tags", "referenceParentCompany", "referenceSubsidiaryCompanies", "dataConnections"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Company from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of reference_parent_company + if self.reference_parent_company: + _dict['referenceParentCompany'] = self.reference_parent_company.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in reference_subsidiary_companies (list) + _items = [] + if self.reference_subsidiary_companies: + for _item_reference_subsidiary_companies in self.reference_subsidiary_companies: + if _item_reference_subsidiary_companies: + _items.append(_item_reference_subsidiary_companies.to_dict()) + _dict['referenceSubsidiaryCompanies'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in data_connections (list) + _items = [] + if self.data_connections: + for _item_data_connections in self.data_connections: + if _item_data_connections: + _items.append(_item_data_connections.to_dict()) + _dict['dataConnections'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Company from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name"), + "description": obj.get("description"), + "redirect": obj.get("redirect"), + "lastSync": obj.get("lastSync"), + "created": obj.get("created"), + "createdByUserName": obj.get("createdByUserName"), + "products": obj.get("products"), + "tags": obj.get("tags"), + "referenceParentCompany": CompanyReference.from_dict(obj["referenceParentCompany"]) if obj.get("referenceParentCompany") is not None else None, + "referenceSubsidiaryCompanies": [CompanyReference.from_dict(_item) for _item in obj["referenceSubsidiaryCompanies"]] if obj.get("referenceSubsidiaryCompanies") is not None else None, + "dataConnections": [Connection.from_dict(_item) for _item in obj["dataConnections"]] if obj.get("dataConnections") is not None else None + }) + return _obj - created_by_user_name: Annotated[ - OptionalNullable[str], pydantic.Field(alias="createdByUserName") - ] = UNSET - r"""Name of user that created the company in Codat.""" - - products: Optional[List[str]] = None - r"""An array of products that are currently enabled for the company.""" - - tags: Optional[Dict[str, str]] = None - r"""A collection of user-defined key-value pairs that store custom metadata against the company.""" - reference_parent_company: Annotated[ - Optional[CompanyReference], pydantic.Field(alias="referenceParentCompany") - ] = None - reference_subsidiary_companies: Annotated[ - Optional[List[CompanyReference]], - pydantic.Field(alias="referenceSubsidiaryCompanies"), - ] = None - r"""A list of subsidiary companies owned or controlled by this entity. Empty if the company has no children.""" - data_connections: Annotated[ - Optional[List[Connection]], pydantic.Field(alias="dataConnections") - ] = None - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "description", - "lastSync", - "created", - "createdByUserName", - "products", - "tags", - "referenceParentCompany", - "referenceSubsidiaryCompanies", - "dataConnections", - ] - ) - nullable_fields = set(["createdByUserName"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - Company.model_rebuild() -except NameError: - pass +class CompanyTypedDict(TypedDict): + """TypedDict variant of Company, for dict-literal request/response inputs.""" + id: NotRequired[str] + name: NotRequired[str] + description: NotRequired[Optional[str]] + redirect: NotRequired[str] + last_sync: NotRequired[Optional[str]] + created: NotRequired[Optional[str]] + created_by_user_name: NotRequired[Optional[str]] + products: NotRequired[Optional[List[str]]] + tags: NotRequired[Optional[Dict[str, str]]] + reference_parent_company: NotRequired[Optional[CompanyReferenceTypedDict]] + reference_subsidiary_companies: NotRequired[Optional[List[CompanyReferenceTypedDict]]] + data_connections: NotRequired[Optional[List[ConnectionTypedDict]]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/companyinformation.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/companyinformation.py index f84e48da1..89f77e8b4 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/companyinformation.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/companyinformation.py @@ -1,67 +1,107 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_payables.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Bill pay (synchronous solution) + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | -class CompanyInformationTypedDict(TypedDict): - r"""Gets the latest basic info for a company.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - company_name: NotRequired[Nullable[str]] - r"""Name of the linked company.""" - base_currency: NotRequired[Nullable[str]] - r"""Currency set in the accounting software of the linked company. Used by the currency rate.""" + Do not edit the class manually. +""" # noqa: E501 -class CompanyInformation(BaseModel): - r"""Gets the latest basic info for a company.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - company_name: Annotated[ - OptionalNullable[str], pydantic.Field(alias="companyName") - ] = UNSET - r"""Name of the linked company.""" +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict - base_currency: Annotated[ - OptionalNullable[str], pydantic.Field(alias="baseCurrency") - ] = UNSET - r"""Currency set in the accounting software of the linked company. Used by the currency rate.""" +from codat_sync_for_payables.types import OptionalNullable, UNSET, UNSET_SENTINEL +class CompanyInformation(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["companyName", "baseCurrency"]) - nullable_fields = set(["companyName", "baseCurrency"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - CompanyInformation.model_rebuild() -except NameError: - pass + _nullable = {'baseCurrency', 'base_currency', 'companyName', 'company_name'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + Gets the latest basic info for a company. + """ # noqa: E501 + company_name: OptionalNullable[str] = Field(default=UNSET, description="Name of the linked company.", alias="companyName") + base_currency: OptionalNullable[str] = Field(default=UNSET, description="Currency set in the accounting software of the linked company. Used by the currency rate.", alias="baseCurrency") + __properties: ClassVar[List[str]] = ["companyName", "baseCurrency"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CompanyInformation from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CompanyInformation from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "companyName": obj.get("companyName"), + "baseCurrency": obj.get("baseCurrency") + }) + return _obj + + + + + +class CompanyInformationTypedDict(TypedDict): + """TypedDict variant of CompanyInformation, for dict-literal request/response inputs.""" + company_name: NotRequired[Optional[str]] + base_currency: NotRequired[Optional[str]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/companyreference.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/companyreference.py index 955a899e5..9ba8b7c0a 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/companyreference.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/companyreference.py @@ -1,83 +1,116 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_payables.types import BaseModel, UNSET_SENTINEL -from pydantic import model_serializer -from typing import Dict, Optional -from typing_extensions import NotRequired, TypedDict +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) -class CompanyReferenceLinksTypedDict(TypedDict): - r"""A collection of links for the company.""" + Do not edit the class manually. +""" # noqa: E501 - portal: NotRequired[str] - r"""Link to the company page in the portal.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json -class CompanyReferenceLinks(BaseModel): - r"""A collection of links for the company.""" +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated, NotRequired, TypedDict +from codat_sync_for_payables.models.company_reference_links import CompanyReferenceLinks, CompanyReferenceLinksTypedDict +from typing import Optional, Set +from typing_extensions import Self - portal: Optional[str] = None - r"""Link to the company page in the portal.""" +class CompanyReference(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["portal"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + CompanyReference + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Unique identifier for your SMB in Codat.") + name: Optional[str] = Field(default=None, description="Name of the bank account in the accounting software.") + description: Optional[str] = Field(default=None, description="Additional information about the company. This can be used to store foreign IDs, references, etc.") + links: Optional[CompanyReferenceLinks] = None + tags: Optional[Dict[str, str]] = Field(default=None, description="A collection of user-defined key-value pairs that store custom metadata against the company.") + __properties: ClassVar[List[str]] = ["id", "name", "description", "links", "tags"] - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - return m + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) -class CompanyReferenceTypedDict(TypedDict): - id: NotRequired[str] - r"""Unique identifier for your SMB in Codat.""" - name: NotRequired[str] - r"""The name of the company""" - description: NotRequired[str] - r"""Additional information about the company. This can be used to store foreign IDs, references, etc.""" - links: NotRequired[CompanyReferenceLinksTypedDict] - r"""A collection of links for the company.""" - tags: NotRequired[Dict[str, str]] - r"""A collection of user-defined key-value pairs that store custom metadata against the company.""" + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CompanyReference from a JSON string""" + return cls.from_dict(json.loads(json_str)) + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. -class CompanyReference(BaseModel): - id: Optional[str] = None - r"""Unique identifier for your SMB in Codat.""" + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - name: Optional[str] = None - r"""The name of the company""" + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) - description: Optional[str] = None - r"""Additional information about the company. This can be used to store foreign IDs, references, etc.""" + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of links + if self.links: + _dict['links'] = self.links.to_dict() + return _dict - links: Optional[CompanyReferenceLinks] = None - r"""A collection of links for the company.""" + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CompanyReference from a dict""" + if obj is None: + return None - tags: Optional[Dict[str, str]] = None - r"""A collection of user-defined key-value pairs that store custom metadata against the company.""" + if not isinstance(obj, dict): + return cls.model_validate(obj) - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["id", "name", "description", "links", "tags"]) - serialized = handler(self) - m = {} + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name"), + "description": obj.get("description"), + "links": CompanyReferenceLinks.from_dict(obj["links"]) if obj.get("links") is not None else None, + "tags": obj.get("tags") + }) + return _obj - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - return m + + +class CompanyReferenceTypedDict(TypedDict): + """TypedDict variant of CompanyReference, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + name: NotRequired[Optional[str]] + description: NotRequired[Optional[str]] + links: NotRequired[Optional[CompanyReferenceLinksTypedDict]] + tags: NotRequired[Optional[Dict[str, str]]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/companyrequestbody.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/companyrequestbody.py index 76dc20cc3..cd5cb3f12 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/companyrequestbody.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/companyrequestbody.py @@ -1,43 +1,113 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_payables.types import BaseModel, UNSET_SENTINEL -from pydantic import model_serializer -from typing import Dict, Optional -from typing_extensions import NotRequired, TypedDict +""" + Bill pay (synchronous solution) + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | -class CompanyRequestBodyTypedDict(TypedDict): - name: str - r"""Name of company being connected.""" - description: NotRequired[str] - r"""Additional information about the company. This can be used to store foreign IDs, references, etc.""" - tags: NotRequired[Dict[str, str]] - r"""A collection of user-defined key-value pairs that store custom metadata against the company.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class CompanyRequestBody(BaseModel): - name: str - r"""Name of company being connected.""" - description: Optional[str] = None - r"""Additional information about the company. This can be used to store foreign IDs, references, etc.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated, NotRequired, TypedDict +from typing import Optional, Set +from typing_extensions import Self - tags: Optional[Dict[str, str]] = None - r"""A collection of user-defined key-value pairs that store custom metadata against the company.""" +class CompanyRequestBody(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["description", "tags"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + CompanyRequestBody + """ # noqa: E501 + name: str = Field(description="Name of company being connected.") + description: Optional[str] = Field(default=None, description="Additional information about the company. This can be used to store foreign IDs, references, etc.") + tags: Optional[Dict[str, str]] = Field(default=None, description="A collection of user-defined key-value pairs that store custom metadata against the company.") + __properties: ClassVar[List[str]] = ["name", "description", "tags"] + + @field_validator('name') + def name_validate_regular_expression(cls, value): + """Validates the regular expression""" + if not re.match(r"^[A-Za-z0-9\s\-\',&@.,?!\s]+$", value): + raise ValueError(r"must validate the regular expression /^[A-Za-z0-9\s\-',&@.,?!\s]+$/") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CompanyRequestBody from a JSON string""" + return cls.from_dict(json.loads(json_str)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - return m + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CompanyRequestBody from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name"), + "description": obj.get("description"), + "tags": obj.get("tags") + }) + return _obj + + + + + +class CompanyRequestBodyTypedDict(TypedDict): + """TypedDict variant of CompanyRequestBody, for dict-literal request/response inputs.""" + name: NotRequired[str] + description: NotRequired[Optional[str]] + tags: NotRequired[Optional[Dict[str, str]]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/companyupdaterequest.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/companyupdaterequest.py index c80c2629e..6ecc74be0 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/companyupdaterequest.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/companyupdaterequest.py @@ -1,43 +1,116 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_payables.types import BaseModel, UNSET_SENTINEL -from pydantic import model_serializer -from typing import Dict, Optional -from typing_extensions import NotRequired, TypedDict +""" + Bill pay (synchronous solution) + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | -class CompanyUpdateRequestTypedDict(TypedDict): - name: NotRequired[str] - r"""Name of company being connected.""" - description: NotRequired[str] - r"""Additional information about the company. This can be used to store foreign IDs, references, etc.""" - tags: NotRequired[Dict[str, str]] - r"""A collection of user-defined key-value pairs that store custom metadata against the company.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class CompanyUpdateRequest(BaseModel): - name: Optional[str] = None - r"""Name of company being connected.""" - description: Optional[str] = None - r"""Additional information about the company. This can be used to store foreign IDs, references, etc.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated, NotRequired, TypedDict +from typing import Optional, Set +from typing_extensions import Self - tags: Optional[Dict[str, str]] = None - r"""A collection of user-defined key-value pairs that store custom metadata against the company.""" +class CompanyUpdateRequest(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["name", "description", "tags"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + CompanyUpdateRequest + """ # noqa: E501 + name: Optional[str] = Field(default=None, description="Name of company being connected.") + description: Optional[str] = Field(default=None, description="Additional information about the company. This can be used to store foreign IDs, references, etc.") + tags: Optional[Dict[str, str]] = Field(default=None, description="A collection of user-defined key-value pairs that store custom metadata against the company.") + __properties: ClassVar[List[str]] = ["name", "description", "tags"] + + @field_validator('name') + def name_validate_regular_expression(cls, value): + """Validates the regular expression""" + if value is None: + return value + + if not re.match(r"^[A-Za-z0-9\s\-\',&@.,?!\s]+$", value): + raise ValueError(r"must validate the regular expression /^[A-Za-z0-9\s\-',&@.,?!\s]+$/") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CompanyUpdateRequest from a JSON string""" + return cls.from_dict(json.loads(json_str)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - return m + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CompanyUpdateRequest from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name"), + "description": obj.get("description"), + "tags": obj.get("tags") + }) + return _obj + + + + + +class CompanyUpdateRequestTypedDict(TypedDict): + """TypedDict variant of CompanyUpdateRequest, for dict-literal request/response inputs.""" + name: NotRequired[Optional[str]] + description: NotRequired[Optional[str]] + tags: NotRequired[Optional[Dict[str, str]]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/connection.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/connection.py index e4413479e..1933c8add 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/connection.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/connection.py @@ -1,230 +1,168 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .dataconnectionerror import DataConnectionError, DataConnectionErrorTypedDict -from .dataconnectionstatus import DataConnectionStatus -from codat_sync_for_payables.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from enum import Enum -import pydantic -from pydantic import model_serializer -from typing import Any, Dict, List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class SourceType(str, Enum): - r"""The type of platform of the connection.""" - - ACCOUNTING = "Accounting" - BANKING = "Banking" - BANK_FEED = "BankFeed" - COMMERCE = "Commerce" - EXPENSE = "Expense" - OTHER = "Other" - UNKNOWN = "Unknown" - - -class ConnectionTypedDict(TypedDict): - r"""A connection represents a [company's](https://docs.codat.io/sync-for-payables-api#/schemas/Company) connection to a data source and allows you to synchronize data (pull and/or push) with that source. - - A company can have multiple data connections depending on the type of data source it is connecting to. For example, a single company can link to: - - - [Accounting data](https://docs.codat.io/accounting-api/overview) - 1 active connection. - - [Banking data](https://docs.codat.io/banking-api/overview) - Multiple active connections. - - [Commerce data](https://docs.codat.io/commerce-api/overview) - Multiple active connections. - Any combination of accounting, banking, and commerce data connections is allowed. - - Before you can use a data connection to pull or push data, the company must grant you access to their business data by [linking the connection](https://docs.codat.io/auth-flow/overview). - """ - - id: str - r"""Unique identifier for a company's data connection.""" - integration_id: str - r"""A Codat ID representing the integration.""" - source_id: str - r"""A source-specific ID used to distinguish between different sources originating from the same data connection. In general, a data connection is a single data source. However, for TrueLayer, `sourceId` is associated with a specific bank and has a many-to-one relationship with the `integrationId`.""" - source_type: SourceType - r"""The type of platform of the connection.""" - platform_name: str - r"""Name of integration connected to company.""" - link_url: str - r"""The link URL your customers can use to authorize access to their business application.""" - status: DataConnectionStatus - r"""The current authorization status of the data connection.""" - created: str - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` +""" + Bill pay (synchronous solution) + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - integration_key: NotRequired[str] - r"""A unique four-character ID that identifies the platform of the company's data connection. This ensures continuity if the platform changes its name in the future.""" - last_sync: NotRequired[str] - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` - - - - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - data_connection_errors: NotRequired[Nullable[List[DataConnectionErrorTypedDict]]] - connection_info: NotRequired[Nullable[Dict[str, Any]]] + Do not edit the class manually. +""" # noqa: E501 +from __future__ import annotations +from codat_sync_for_payables.models.source_type import SourceType +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_sync_for_payables.models.shared.dataconnectionerror import DataConnectionError, DataConnectionErrorTypedDict +from codat_sync_for_payables.models.shared.dataconnectionstatus import DataConnectionStatus +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_sync_for_payables.types import OptionalNullable, UNSET, UNSET_SENTINEL class Connection(BaseModel): - r"""A connection represents a [company's](https://docs.codat.io/sync-for-payables-api#/schemas/Company) connection to a data source and allows you to synchronize data (pull and/or push) with that source. - - A company can have multiple data connections depending on the type of data source it is connecting to. For example, a single company can link to: - - - [Accounting data](https://docs.codat.io/accounting-api/overview) - 1 active connection. - - [Banking data](https://docs.codat.io/banking-api/overview) - Multiple active connections. - - [Commerce data](https://docs.codat.io/commerce-api/overview) - Multiple active connections. - Any combination of accounting, banking, and commerce data connections is allowed. - Before you can use a data connection to pull or push data, the company must grant you access to their business data by [linking the connection](https://docs.codat.io/auth-flow/overview). + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'connectionInfo', 'connection_info', 'dataConnectionErrors', 'data_connection_errors'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } """ - - id: str - r"""Unique identifier for a company's data connection.""" - - integration_id: Annotated[str, pydantic.Field(alias="integrationId")] - r"""A Codat ID representing the integration.""" - - source_id: Annotated[str, pydantic.Field(alias="sourceId")] - r"""A source-specific ID used to distinguish between different sources originating from the same data connection. In general, a data connection is a single data source. However, for TrueLayer, `sourceId` is associated with a specific bank and has a many-to-one relationship with the `integrationId`.""" - - source_type: Annotated[SourceType, pydantic.Field(alias="sourceType")] - r"""The type of platform of the connection.""" - - platform_name: Annotated[str, pydantic.Field(alias="platformName")] - r"""Name of integration connected to company.""" - - link_url: Annotated[str, pydantic.Field(alias="linkUrl")] - r"""The link URL your customers can use to authorize access to their business application.""" - + A connection represents a [company's](https://docs.codat.io/sync-for-payables-api#/schemas/Company) connection to a data source and allows you to synchronize data (pull and/or push) with that source. A company can have multiple data connections depending on the type of data source it is connecting to. For example, a single company can link to: - [Accounting data](https://docs.codat.io/accounting-api/overview) - 1 active connection. - [Banking data](https://docs.codat.io/banking-api/overview) - Multiple active connections. - [Commerce data](https://docs.codat.io/commerce-api/overview) - Multiple active connections. Any combination of accounting, banking, and commerce data connections is allowed. Before you can use a data connection to pull or push data, the company must grant you access to their business data by [linking the connection](https://docs.codat.io/auth-flow/overview). + """ # noqa: E501 + id: str = Field(description="Unique identifier for a company's data connection.") + integration_id: str = Field(description="A Codat ID representing the integration.", alias="integrationId") + integration_key: Optional[str] = Field(default=None, description="A unique four-character ID that identifies the platform of the company's data connection. This ensures continuity if the platform changes its name in the future.", alias="integrationKey") + source_id: str = Field(description="A source-specific ID used to distinguish between different sources originating from the same data connection. In general, a data connection is a single data source. However, for TrueLayer, `sourceId` is associated with a specific bank and has a many-to-one relationship with the `integrationId`.", alias="sourceId") + source_type: SourceType = Field(description="The type of platform of the connection.", alias="sourceType") + platform_name: str = Field(description="Name of integration connected to company.", alias="platformName") + link_url: str = Field(description="The link URL your customers can use to authorize access to their business application.", alias="linkUrl") status: DataConnectionStatus - r"""The current authorization status of the data connection.""" - - created: str - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` - - - - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - - integration_key: Annotated[ - Optional[str], pydantic.Field(alias="integrationKey") - ] = None - r"""A unique four-character ID that identifies the platform of the company's data connection. This ensures continuity if the platform changes its name in the future.""" - - last_sync: Annotated[Optional[str], pydantic.Field(alias="lastSync")] = None - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` - - + last_sync: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.", alias="lastSync") + created: str = Field(description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.") + data_connection_errors: OptionalNullable[List[DataConnectionError]] = Field(default=UNSET, alias="dataConnectionErrors") + connection_info: OptionalNullable[Dict[str, Any]] = Field(default=UNSET, alias="connectionInfo") + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["id", "integrationId", "integrationKey", "sourceId", "sourceType", "platformName", "linkUrl", "status", "lastSync", "created", "dataConnectionErrors", "connectionInfo"] + + @field_validator('source_type') + def source_type_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['Accounting', 'Banking', 'BankFeed', 'Commerce', 'Expense', 'Other', 'Unknown']): + raise ValueError("must be one of enum values ('Accounting', 'Banking', 'BankFeed', 'Commerce', 'Expense', 'Other', 'Unknown')") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Connection from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + * Fields in `self.additional_properties` are added to the output dict. + """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in data_connection_errors (list) + _items = [] + if self.data_connection_errors: + for _item_data_connection_errors in self.data_connection_errors: + if _item_data_connection_errors: + _items.append(_item_data_connection_errors.to_dict()) + _dict['dataConnectionErrors'] = _items + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Connection from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "integrationId": obj.get("integrationId"), + "integrationKey": obj.get("integrationKey"), + "sourceId": obj.get("sourceId"), + "sourceType": obj.get("sourceType"), + "platformName": obj.get("platformName"), + "linkUrl": obj.get("linkUrl"), + "status": obj.get("status"), + "lastSync": obj.get("lastSync"), + "created": obj.get("created"), + "dataConnectionErrors": [DataConnectionError.from_dict(_item) for _item in obj["dataConnectionErrors"]] if obj.get("dataConnectionErrors") is not None else None, + "connectionInfo": obj.get("connectionInfo") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - data_connection_errors: Annotated[ - OptionalNullable[List[DataConnectionError]], - pydantic.Field(alias="dataConnectionErrors"), - ] = UNSET - connection_info: Annotated[ - OptionalNullable[Dict[str, Any]], pydantic.Field(alias="connectionInfo") - ] = UNSET - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - ["integrationKey", "lastSync", "dataConnectionErrors", "connectionInfo"] - ) - nullable_fields = set(["dataConnectionErrors", "connectionInfo"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - Connection.model_rebuild() -except NameError: - pass +class ConnectionTypedDict(TypedDict): + """TypedDict variant of Connection, for dict-literal request/response inputs.""" + id: NotRequired[str] + integration_id: NotRequired[str] + integration_key: NotRequired[Optional[str]] + source_id: NotRequired[str] + source_type: NotRequired[SourceType] + platform_name: NotRequired[str] + link_url: NotRequired[str] + status: DataConnectionStatus + last_sync: NotRequired[Optional[str]] + created: NotRequired[str] + data_connection_errors: NotRequired[Optional[List[DataConnectionErrorTypedDict]]] + connection_info: NotRequired[Optional[Dict[str, Any]]] + additional_properties: NotRequired[Dict[str, Any]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/connections.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/connections.py index 6696c0949..67b6f4c0d 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/connections.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/connections.py @@ -1,58 +1,124 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations -from .connection import Connection, ConnectionTypedDict -from .links import Links, LinksTypedDict -from codat_sync_for_payables.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import List, Optional +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional from typing_extensions import Annotated, NotRequired, TypedDict +from codat_sync_for_payables.models.shared.connection import Connection, ConnectionTypedDict +from codat_sync_for_payables.models.shared.links import Links, LinksTypedDict +from typing import Optional, Set +from typing_extensions import Self +class Connections(BaseModel): -class ConnectionsTypedDict(TypedDict): - page_number: int - r"""Current page number.""" - page_size: int - r"""Number of items to return in results array.""" - total_results: int - r"""Total number of items.""" - links: LinksTypedDict - results: NotRequired[List[ConnectionTypedDict]] + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + Connections + """ # noqa: E501 + page_number: int = Field(description="Current page number.", alias="pageNumber") + page_size: int = Field(description="Number of items to return in results array.", alias="pageSize") + total_results: int = Field(description="Total number of items.", alias="totalResults") + links: Links = Field(alias="_links") + results: Optional[List[Connection]] = None + __properties: ClassVar[List[str]] = ["pageNumber", "pageSize", "totalResults", "_links", "results"] + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) -class Connections(BaseModel): - page_number: Annotated[int, pydantic.Field(alias="pageNumber")] - r"""Current page number.""" - page_size: Annotated[int, pydantic.Field(alias="pageSize")] - r"""Number of items to return in results array.""" + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - total_results: Annotated[int, pydantic.Field(alias="totalResults")] - r"""Total number of items.""" + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - links: Annotated[Links, pydantic.Field(alias="_links")] + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Connections from a JSON string""" + return cls.from_dict(json.loads(json_str)) - results: Optional[List[Connection]] = None + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["results"]) - serialized = handler(self) - m = {} + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of links + if self.links: + _dict['_links'] = self.links.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in results (list) + _items = [] + if self.results: + for _item_results in self.results: + if _item_results: + _items.append(_item_results.to_dict()) + _dict['results'] = _items + return _dict - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Connections from a dict""" + if obj is None: + return None - return m + if not isinstance(obj, dict): + return cls.model_validate(obj) + _obj = cls.model_validate({ + "pageNumber": obj.get("pageNumber"), + "pageSize": obj.get("pageSize"), + "totalResults": obj.get("totalResults"), + "_links": Links.from_dict(obj["_links"]) if obj.get("_links") is not None else None, + "results": [Connection.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None + }) + return _obj -try: - Connections.model_rebuild() -except NameError: - pass + + + + +class ConnectionsTypedDict(TypedDict): + """TypedDict variant of Connections, for dict-literal request/response inputs.""" + page_number: NotRequired[int] + page_size: NotRequired[int] + total_results: NotRequired[int] + links: NotRequired[LinksTypedDict] + results: NotRequired[Optional[List[ConnectionTypedDict]]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/dataconnectionerror.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/dataconnectionerror.py index 887535143..9b5aad5ed 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/dataconnectionerror.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/dataconnectionerror.py @@ -1,177 +1,130 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_payables.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from enum import Enum -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class ErrorStatus(str, Enum): - r"""The current status of a transient error. Null statuses indicate that the error is not transient.""" - - ACTIVE = "Active" - RESOLVED = "Resolved" - - -class DataConnectionErrorTypedDict(TypedDict): - status_code: NotRequired[str] - r"""The HTTP status code returned by the source platform when the error occurred.""" - status_text: NotRequired[str] - r"""A non-numeric status code/text returned by the source platform when the error occurred.""" - error_message: NotRequired[str] - r"""A message about a error returned by Codat.""" - errored_on_utc: NotRequired[str] - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` +""" + Bill pay (synchronous solution) + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: + Do not edit the class manually. +""" # noqa: E501 - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - status: NotRequired[Nullable[ErrorStatus]] - r"""The current status of a transient error. Null statuses indicate that the error is not transient.""" - resolved_on_utc: NotRequired[str] - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` - - - - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ +from __future__ import annotations +from codat_sync_for_payables.models.error_status import ErrorStatus +import pprint +import re # noqa: F401 +import json +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict +from codat_sync_for_payables.types import OptionalNullable, UNSET, UNSET_SENTINEL class DataConnectionError(BaseModel): - status_code: Annotated[Optional[str], pydantic.Field(alias="statusCode")] = None - r"""The HTTP status code returned by the source platform when the error occurred.""" - - status_text: Annotated[Optional[str], pydantic.Field(alias="statusText")] = None - r"""A non-numeric status code/text returned by the source platform when the error occurred.""" - error_message: Annotated[Optional[str], pydantic.Field(alias="errorMessage")] = None - r"""A message about a error returned by Codat.""" - - errored_on_utc: Annotated[Optional[str], pydantic.Field(alias="erroredOnUtc")] = ( - None + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'status'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + DataConnectionError + """ # noqa: E501 + status_code: Optional[str] = Field(default=None, description="The HTTP status code returned by the source platform when the error occurred.", alias="statusCode") + status_text: Optional[str] = Field(default=None, description="A non-numeric status code/text returned by the source platform when the error occurred.", alias="statusText") + error_message: Optional[str] = Field(default=None, description="A message about a error returned by Codat.", alias="errorMessage") + errored_on_utc: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.", alias="erroredOnUtc") + status: OptionalNullable[ErrorStatus] = Field(default=UNSET, description="The current status of a transient error. Null statuses indicate that the error is not transient.") + resolved_on_utc: Optional[str] = Field(default=None, description="In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: ``` 2020-10-08T22:40:50Z 2021-01-01T00:00:00 ``` When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - Unqualified local time: `2021-11-15T01:00:00` - UTC time offsets: `2021-11-15T01:00:00-05:00` > Time zones > > Not all dates from Codat will contain information about time zones. > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced.", alias="resolvedOnUtc") + __properties: ClassVar[List[str]] = ["statusCode", "statusText", "errorMessage", "erroredOnUtc", "status", "resolvedOnUtc"] + + @field_validator('status') + def status_validate_enum(cls, value): + """Validates the enum""" + if value is None: + return value + + if value not in set(['Active', 'Resolved']): + raise ValueError("must be one of enum values ('Active', 'Resolved')") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), ) - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of DataConnectionError from a JSON string""" + return cls.from_dict(json.loads(json_str)) - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - status: OptionalNullable[ErrorStatus] = UNSET - r"""The current status of a transient error. Null statuses indicate that the error is not transient.""" + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) - resolved_on_utc: Annotated[Optional[str], pydantic.Field(alias="resolvedOnUtc")] = ( - None - ) - r"""In Codat's data model, dates and times are represented using the ISO 8601 standard. Date and time fields are formatted as strings; for example: + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of DataConnectionError from a dict""" + if obj is None: + return None + if not isinstance(obj, dict): + return cls.model_validate(obj) + _obj = cls.model_validate({ + "statusCode": obj.get("statusCode"), + "statusText": obj.get("statusText"), + "errorMessage": obj.get("errorMessage"), + "erroredOnUtc": obj.get("erroredOnUtc"), + "status": obj.get("status"), + "resolvedOnUtc": obj.get("resolvedOnUtc") + }) + return _obj - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: - - Coordinated Universal Time (UTC): `2021-11-15T06:00:00Z` - - Unqualified local time: `2021-11-15T01:00:00` - - UTC time offsets: `2021-11-15T01:00:00-05:00` - > Time zones - > - > Not all dates from Codat will contain information about time zones. - > Where it is not available from the underlying platform, Codat will return these as times local to the business whose data has been synced. - """ - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "statusCode", - "statusText", - "errorMessage", - "erroredOnUtc", - "status", - "resolvedOnUtc", - ] - ) - nullable_fields = set(["status"]) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - DataConnectionError.model_rebuild() -except NameError: - pass + +class DataConnectionErrorTypedDict(TypedDict): + """TypedDict variant of DataConnectionError, for dict-literal request/response inputs.""" + status_code: NotRequired[Optional[str]] + status_text: NotRequired[Optional[str]] + error_message: NotRequired[Optional[str]] + errored_on_utc: NotRequired[Optional[str]] + status: NotRequired[Optional[ErrorStatus]] + resolved_on_utc: NotRequired[Optional[str]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/dataconnectionstatus.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/dataconnectionstatus.py index a97f7be30..bf23bfe93 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/dataconnectionstatus.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/dataconnectionstatus.py @@ -1,13 +1,40 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations +import json from enum import Enum +from typing_extensions import Self class DataConnectionStatus(str, Enum): - r"""The current authorization status of the data connection.""" + """ + The current authorization status of the data connection. + """ + + """ + allowed enum values + """ + PENDING_AUTH = 'PendingAuth' + LINKED = 'Linked' + UNLINKED = 'Unlinked' + DEAUTHORIZED = 'Deauthorized' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of DataConnectionStatus from a JSON string""" + return cls(json.loads(json_str)) + - PENDING_AUTH = "PendingAuth" - LINKED = "Linked" - UNLINKED = "Unlinked" - DEAUTHORIZED = "Deauthorized" diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/errorvalidation.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/errorvalidation.py index ab8d4c61f..507ee18c1 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/errorvalidation.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/errorvalidation.py @@ -1,54 +1,122 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .errorvalidationitem import ErrorValidationItem, ErrorValidationItemTypedDict -from codat_sync_for_payables.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from pydantic import model_serializer -from typing import List -from typing_extensions import NotRequired, TypedDict +""" + Bill pay (synchronous solution) + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | -class ErrorValidationTypedDict(TypedDict): - r"""A human-readable object describing validation decisions Codat has made. If an operation has failed because of validation errors, they will be detailed here.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - errors: NotRequired[Nullable[List[ErrorValidationItemTypedDict]]] - warnings: NotRequired[Nullable[List[ErrorValidationItemTypedDict]]] + Do not edit the class manually. +""" # noqa: E501 -class ErrorValidation(BaseModel): - r"""A human-readable object describing validation decisions Codat has made. If an operation has failed because of validation errors, they will be detailed here.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - errors: OptionalNullable[List[ErrorValidationItem]] = UNSET +from pydantic import BaseModel, ConfigDict, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_sync_for_payables.models.shared.errorvalidationitem import ErrorValidationItem, ErrorValidationItemTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict - warnings: OptionalNullable[List[ErrorValidationItem]] = UNSET +from codat_sync_for_payables.types import OptionalNullable, UNSET, UNSET_SENTINEL +class ErrorValidation(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["errors", "warnings"]) - nullable_fields = set(["errors", "warnings"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m + _nullable = {'errors', 'warnings'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + A human-readable object describing validation decisions Codat has made. If an operation has failed because of validation errors, they will be detailed here. + """ # noqa: E501 + errors: OptionalNullable[List[ErrorValidationItem]] = UNSET + warnings: OptionalNullable[List[ErrorValidationItem]] = UNSET + __properties: ClassVar[List[str]] = ["errors", "warnings"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ErrorValidation from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in errors (list) + _items = [] + if self.errors: + for _item_errors in self.errors: + if _item_errors: + _items.append(_item_errors.to_dict()) + _dict['errors'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in warnings (list) + _items = [] + if self.warnings: + for _item_warnings in self.warnings: + if _item_warnings: + _items.append(_item_warnings.to_dict()) + _dict['warnings'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ErrorValidation from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "errors": [ErrorValidationItem.from_dict(_item) for _item in obj["errors"]] if obj.get("errors") is not None else None, + "warnings": [ErrorValidationItem.from_dict(_item) for _item in obj["warnings"]] if obj.get("warnings") is not None else None + }) + return _obj + + + + + +class ErrorValidationTypedDict(TypedDict): + """TypedDict variant of ErrorValidation, for dict-literal request/response inputs.""" + errors: NotRequired[Optional[List[ErrorValidationItemTypedDict]]] + warnings: NotRequired[Optional[List[ErrorValidationItemTypedDict]]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/errorvalidationitem.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/errorvalidationitem.py index 59ce442a3..997d5fa9a 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/errorvalidationitem.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/errorvalidationitem.py @@ -1,66 +1,110 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_payables.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Bill pay (synchronous solution) + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | -class ErrorValidationItemTypedDict(TypedDict): - item_id: NotRequired[Nullable[str]] - r"""Unique identifier for a validation item.""" - message: NotRequired[Nullable[str]] - r"""A message outlining validation item's issue.""" - validator_name: NotRequired[Nullable[str]] - r"""Name of validator.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class ErrorValidationItem(BaseModel): - item_id: Annotated[OptionalNullable[str], pydantic.Field(alias="itemId")] = UNSET - r"""Unique identifier for a validation item.""" - message: OptionalNullable[str] = UNSET - r"""A message outlining validation item's issue.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict - validator_name: Annotated[ - OptionalNullable[str], pydantic.Field(alias="validatorName") - ] = UNSET - r"""Name of validator.""" +from codat_sync_for_payables.types import OptionalNullable, UNSET, UNSET_SENTINEL +class ErrorValidationItem(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["itemId", "message", "validatorName"]) - nullable_fields = set(["itemId", "message", "validatorName"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - ErrorValidationItem.model_rebuild() -except NameError: - pass + _nullable = {'itemId', 'item_id', 'message', 'validatorName', 'validator_name'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + ErrorValidationItem + """ # noqa: E501 + item_id: OptionalNullable[str] = Field(default=UNSET, description="Unique identifier for a validation item.", alias="itemId") + message: OptionalNullable[str] = Field(default=UNSET, description="A message outlining validation item's issue.") + validator_name: OptionalNullable[str] = Field(default=UNSET, description="Name of validator.", alias="validatorName") + __properties: ClassVar[List[str]] = ["itemId", "message", "validatorName"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ErrorValidationItem from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ErrorValidationItem from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "itemId": obj.get("itemId"), + "message": obj.get("message"), + "validatorName": obj.get("validatorName") + }) + return _obj + + + + + +class ErrorValidationItemTypedDict(TypedDict): + """TypedDict variant of ErrorValidationItem, for dict-literal request/response inputs.""" + item_id: NotRequired[Optional[str]] + message: NotRequired[Optional[str]] + validator_name: NotRequired[Optional[str]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/halref.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/halref.py index dd4b314cd..6e0debca9 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/halref.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/halref.py @@ -1,33 +1,99 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_payables.types import BaseModel, UNSET_SENTINEL -from pydantic import model_serializer -from typing import Optional -from typing_extensions import NotRequired, TypedDict +""" + Bill pay (synchronous solution) + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | -class HalRefTypedDict(TypedDict): - href: NotRequired[str] - r"""Uri hypertext reference.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict class HalRef(BaseModel): - href: Optional[str] = None - r"""Uri hypertext reference.""" @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["href"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + HalRef + """ # noqa: E501 + href: Optional[str] = Field(default=None, description="Uri hypertext reference.") + __properties: ClassVar[List[str]] = ["href"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of HalRef from a JSON string""" + return cls.from_dict(json.loads(json_str)) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - return m + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of HalRef from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "href": obj.get("href") + }) + return _obj + + + + + +class HalRefTypedDict(TypedDict): + """TypedDict variant of HalRef, for dict-literal request/response inputs.""" + href: NotRequired[Optional[str]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/links.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/links.py index 708db8b08..61fafb766 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/links.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/links.py @@ -1,48 +1,121 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .halref import HalRef, HalRefTypedDict -from codat_sync_for_payables.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Bill pay (synchronous solution) + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | -class LinksTypedDict(TypedDict): - self_: HalRefTypedDict - current: HalRefTypedDict - next: NotRequired[HalRefTypedDict] - previous: NotRequired[HalRefTypedDict] + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class Links(BaseModel): - self_: Annotated[HalRef, pydantic.Field(alias="self")] - current: HalRef +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - next: Optional[HalRef] = None +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_sync_for_payables.models.shared.halref import HalRef, HalRefTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict - previous: Optional[HalRef] = None +class Links(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["next", "previous"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + Links + """ # noqa: E501 + self_: HalRef = Field(alias="self") + current: HalRef + next: Optional[HalRef] = None + previous: Optional[HalRef] = None + __properties: ClassVar[List[str]] = ["self", "current", "next", "previous"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - return m + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Links from a JSON string""" + return cls.from_dict(json.loads(json_str)) -try: - Links.model_rebuild() -except NameError: - pass + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of var_self + if self.self_: + _dict['self'] = self.self_.to_dict() + # override the default output from pydantic by calling `to_dict()` of current + if self.current: + _dict['current'] = self.current.to_dict() + # override the default output from pydantic by calling `to_dict()` of next + if self.next: + _dict['next'] = self.next.to_dict() + # override the default output from pydantic by calling `to_dict()` of previous + if self.previous: + _dict['previous'] = self.previous.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Links from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "self": HalRef.from_dict(obj["self"]) if obj.get("self") is not None else None, + "current": HalRef.from_dict(obj["current"]) if obj.get("current") is not None else None, + "next": HalRef.from_dict(obj["next"]) if obj.get("next") is not None else None, + "previous": HalRef.from_dict(obj["previous"]) if obj.get("previous") is not None else None + }) + return _obj + + + + + +class LinksTypedDict(TypedDict): + """TypedDict variant of Links, for dict-literal request/response inputs.""" + self_: NotRequired[HalRefTypedDict] + current: HalRefTypedDict + next: NotRequired[Optional[HalRefTypedDict]] + previous: NotRequired[Optional[HalRefTypedDict]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/pagination.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/pagination.py index d76c207d2..3e13ccd0f 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/pagination.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/pagination.py @@ -1,42 +1,99 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_payables.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Bill pay (synchronous solution) + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | -class PaginationTypedDict(TypedDict): - continuation_token: NotRequired[str] - r"""A continuation token indicating there are more results to be fetched. Supply this value in the `continuationToken` query parameter in the next request to fetch the next set of results. Once no more results are available, the continuation token will not be present in the response.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict class Pagination(BaseModel): - continuation_token: Annotated[ - Optional[str], pydantic.Field(alias="continuationToken") - ] = None - r"""A continuation token indicating there are more results to be fetched. Supply this value in the `continuationToken` query parameter in the next request to fetch the next set of results. Once no more results are available, the continuation token will not be present in the response.""" @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["continuationToken"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + Pagination + """ # noqa: E501 + continuation_token: Optional[str] = Field(default=None, description="A continuation token indicating there are more results to be fetched. Supply this value in the `continuationToken` query parameter in the next request to fetch the next set of results. Once no more results are available, the continuation token will not be present in the response.", alias="continuationToken") + __properties: ClassVar[List[str]] = ["continuationToken"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Pagination from a JSON string""" + return cls.from_dict(json.loads(json_str)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - return m + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) -try: - Pagination.model_rebuild() -except NameError: - pass + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Pagination from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "continuationToken": obj.get("continuationToken") + }) + return _obj + + + + + +class PaginationTypedDict(TypedDict): + """TypedDict variant of Pagination, for dict-literal request/response inputs.""" + continuation_token: NotRequired[Optional[str]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/paymentmappingoptions.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/paymentmappingoptions.py index 6090a5978..472898ca0 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/paymentmappingoptions.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/paymentmappingoptions.py @@ -1,53 +1,115 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .bankaccountmappingoption import ( - BankAccountMappingOption, - BankAccountMappingOptionTypedDict, -) -from .pagination import Pagination, PaginationTypedDict -from codat_sync_for_payables.types import BaseModel, Nullable, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Bill pay (synchronous solution) + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | -class PaymentMappingOptionsTypedDict(TypedDict): - r"""Gets the bill payments mapping options for a company's accounting software""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - bank_accounts: NotRequired[List[Nullable[BankAccountMappingOptionTypedDict]]] - pagination: NotRequired[PaginationTypedDict] + Do not edit the class manually. +""" # noqa: E501 -class PaymentMappingOptions(BaseModel): - r"""Gets the bill payments mapping options for a company's accounting software""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - bank_accounts: Annotated[ - Optional[List[Nullable[BankAccountMappingOption]]], - pydantic.Field(alias="bankAccounts"), - ] = None +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_sync_for_payables.models.shared.bankaccountmappingoption import BankAccountMappingOption, BankAccountMappingOptionTypedDict +from codat_sync_for_payables.models.shared.pagination import Pagination, PaginationTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict - pagination: Optional[Pagination] = None +from codat_sync_for_payables.types import Nullable +class PaymentMappingOptions(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["bankAccounts", "pagination"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + Gets the bill payments mapping options for a company's accounting software + """ # noqa: E501 + bank_accounts: Optional[List[Nullable[BankAccountMappingOption]]] = Field(default=None, alias="bankAccounts") + pagination: Optional[Pagination] = None + __properties: ClassVar[List[str]] = ["bankAccounts", "pagination"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of PaymentMappingOptions from a JSON string""" + return cls.from_dict(json.loads(json_str)) - return m + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: -try: - PaymentMappingOptions.model_rebuild() -except NameError: - pass + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in bank_accounts (list) + _items = [] + if self.bank_accounts: + for _item_bank_accounts in self.bank_accounts: + if _item_bank_accounts: + _items.append(_item_bank_accounts.to_dict()) + _dict['bankAccounts'] = _items + # override the default output from pydantic by calling `to_dict()` of pagination + if self.pagination: + _dict['pagination'] = self.pagination.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of PaymentMappingOptions from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "bankAccounts": [BankAccountMappingOption.from_dict(_item) for _item in obj["bankAccounts"]] if obj.get("bankAccounts") is not None else None, + "pagination": Pagination.from_dict(obj["pagination"]) if obj.get("pagination") is not None else None + }) + return _obj + + + + + +class PaymentMappingOptionsTypedDict(TypedDict): + """TypedDict variant of PaymentMappingOptions, for dict-literal request/response inputs.""" + bank_accounts: NotRequired[Optional[List[Nullable[BankAccountMappingOptionTypedDict]]]] + pagination: NotRequired[Optional[PaginationTypedDict]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/security.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/security.py index 33927c43a..98b9b6ced 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/security.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/security.py @@ -1,9 +1,12 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""Security model for codat_sync_for_payables. + +Generated by pipeline/postprocess_generated.py — do not edit by hand. +""" from __future__ import annotations -from codat_sync_for_payables.types import BaseModel -from codat_sync_for_payables.utils import FieldMetadata, SecurityMetadata -from typing_extensions import Annotated, TypedDict + +from pydantic import BaseModel +from typing_extensions import TypedDict class SecurityTypedDict(TypedDict): @@ -11,14 +14,5 @@ class SecurityTypedDict(TypedDict): class Security(BaseModel): - auth_header: Annotated[ - str, - FieldMetadata( - security=SecurityMetadata( - scheme=True, - scheme_type="apiKey", - sub_type="header", - field_name="Authorization", - ) - ), - ] + auth_header: str + r"""The word "Basic" followed by a space and your API key. [API keys](https://docs.codat.io/platform-api#/schemas/ApiKeyDetails) are tokens used to control access to the API. You can get an API key via [the Codat Portal](https://app.codat.io/developers/api-keys), via [the API](https://docs.codat.io/platform-api#/operations/list-api-keys), or [read more](https://docs.codat.io/using-the-api/authentication) about authentication at Codat.""" diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/supplier.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/supplier.py index ca0db96d7..35e2a7547 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/supplier.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/supplier.py @@ -1,150 +1,142 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .address import Address, AddressTypedDict -from .supplierstatus import SupplierStatus -from codat_sync_for_payables.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from codat_sync_for_payables.utils import serialize_decimal, validate_decimal -from decimal import Decimal -import pydantic -from pydantic import model_serializer -from pydantic.functional_serializers import PlainSerializer -from pydantic.functional_validators import BeforeValidator -from typing import List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Bill pay (synchronous solution) + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | -class SupplierTypedDict(TypedDict): - r"""Suppliers are people or organizations that provide something, such as a product or service. Use the [List suppliers](https://docs.codat.io/sync-for-payables-v2-api#/operations/list-suppliers) endpoint to retrieve a list of all suppliers for a company. + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - Suppliers' data links to accounts payable [bills](https://docs.codat.io/sync-for-payables-v2-api#/schemas/Bill). - - """ - - id: NotRequired[str] - r"""Identifier for the supplier, unique to the company in the accounting software.""" - supplier_name: NotRequired[str] - r"""Name of the supplier as recorded in the accounting system, typically the company name.""" - contact_name: NotRequired[Nullable[str]] - r"""Name of the main contact for the supplier.""" - email_address: NotRequired[Nullable[str]] - r"""Email address that the supplier may be contacted on.""" - phone: NotRequired[Nullable[str]] - r"""Phone number that the supplier may be contacted on.""" - addresses: NotRequired[Nullable[List[AddressTypedDict]]] - r"""An array of Addresses.""" - status: NotRequired[SupplierStatus] - r"""Status of the supplier.""" - balance: NotRequired[Nullable[Decimal]] - r"""Amount outstanding against the supplier.""" - default_currency: NotRequired[Nullable[str]] - r"""Default currency the supplier's transactional data is recorded in.""" - source_modified_date: NotRequired[str] + Do not edit the class manually. +""" # noqa: E501 +from __future__ import annotations +from decimal import Decimal +from codat_sync_for_payables.utils.serializers import serialize_decimal, validate_decimal +import pprint +import re # noqa: F401 +import json + +from pydantic import BeforeValidator, PlainSerializer, BaseModel, ConfigDict, Field, model_serializer +from typing import Annotated, Any, ClassVar, Dict, List, Optional, Union +from codat_sync_for_payables.models.shared.address import Address, AddressTypedDict +from codat_sync_for_payables.models.shared.supplierstatus import SupplierStatus +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_sync_for_payables.types import OptionalNullable, UNSET, UNSET_SENTINEL class Supplier(BaseModel): - r"""Suppliers are people or organizations that provide something, such as a product or service. Use the [List suppliers](https://docs.codat.io/sync-for-payables-v2-api#/operations/list-suppliers) endpoint to retrieve a list of all suppliers for a company. - - Suppliers' data links to accounts payable [bills](https://docs.codat.io/sync-for-payables-v2-api#/schemas/Bill). + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'addresses', 'balance', 'contactName', 'contact_name', 'defaultCurrency', 'default_currency', 'emailAddress', 'email_address', 'phone'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } """ - - id: Optional[str] = None - r"""Identifier for the supplier, unique to the company in the accounting software.""" - - supplier_name: Annotated[Optional[str], pydantic.Field(alias="supplierName")] = None - r"""Name of the supplier as recorded in the accounting system, typically the company name.""" - - contact_name: Annotated[ - OptionalNullable[str], pydantic.Field(alias="contactName") - ] = UNSET - r"""Name of the main contact for the supplier.""" - - email_address: Annotated[ - OptionalNullable[str], pydantic.Field(alias="emailAddress") - ] = UNSET - r"""Email address that the supplier may be contacted on.""" - - phone: OptionalNullable[str] = UNSET - r"""Phone number that the supplier may be contacted on.""" - - addresses: OptionalNullable[List[Address]] = UNSET - r"""An array of Addresses.""" - + Suppliers are people or organizations that provide something, such as a product or service. Use the [List suppliers](https://docs.codat.io/sync-for-payables-v2-api#/operations/list-suppliers) endpoint to retrieve a list of all suppliers for a company. Suppliers' data links to accounts payable [bills](https://docs.codat.io/sync-for-payables-v2-api#/schemas/Bill). + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Identifier for the supplier, unique to the company in the accounting software.") + supplier_name: Optional[str] = Field(default=None, description="Name of the supplier as recorded in the accounting system, typically the company name.", alias="supplierName") + contact_name: OptionalNullable[str] = Field(default=UNSET, description="Name of the main contact for the supplier.", alias="contactName") + email_address: OptionalNullable[str] = Field(default=UNSET, description="Email address that the supplier may be contacted on.", alias="emailAddress") + phone: OptionalNullable[str] = Field(default=UNSET, description="Phone number that the supplier may be contacted on.") + addresses: OptionalNullable[List[Address]] = Field(default=UNSET, description="An array of Addresses.") status: Optional[SupplierStatus] = None - r"""Status of the supplier.""" + balance: Annotated[OptionalNullable[Decimal], BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(default=UNSET, description="Amount outstanding against the supplier.") + default_currency: OptionalNullable[str] = Field(default=UNSET, description="Default currency the supplier's transactional data is recorded in.", alias="defaultCurrency") + source_modified_date: Optional[str] = Field(default=None, description="The date when a record was last modified in the accounting software, usually by the business or a business process. For example, when payments are made against an invoice. It is not populated ([read more](https://docs.codat.io/using-the-api/modified-dates#source-modified-date)) when: - Pulling attachments - The accounting software does not provide modification dates for a data type - A record has been deleted from the source platform and Codat doesn't have a record of when the deletion occurred - A record has been voided. For certain platforms that soft delete records, `isDeleted` metadata is used to identify void records In Codat's data model, dates and times are represented using the ISO 8601 standard.", alias="sourceModifiedDate") + __properties: ClassVar[List[str]] = ["id", "supplierName", "contactName", "emailAddress", "phone", "addresses", "status", "balance", "defaultCurrency", "sourceModifiedDate"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Supplier from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in addresses (list) + _items = [] + if self.addresses: + for _item_addresses in self.addresses: + if _item_addresses: + _items.append(_item_addresses.to_dict()) + _dict['addresses'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Supplier from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "supplierName": obj.get("supplierName"), + "contactName": obj.get("contactName"), + "emailAddress": obj.get("emailAddress"), + "phone": obj.get("phone"), + "addresses": [Address.from_dict(_item) for _item in obj["addresses"]] if obj.get("addresses") is not None else None, + "status": obj.get("status"), + "balance": obj.get("balance"), + "defaultCurrency": obj.get("defaultCurrency"), + "sourceModifiedDate": obj.get("sourceModifiedDate") + }) + return _obj - balance: Annotated[ - OptionalNullable[Decimal], - BeforeValidator(validate_decimal), - PlainSerializer(serialize_decimal(False)), - ] = UNSET - r"""Amount outstanding against the supplier.""" - default_currency: Annotated[ - OptionalNullable[str], pydantic.Field(alias="defaultCurrency") - ] = UNSET - r"""Default currency the supplier's transactional data is recorded in.""" - source_modified_date: Annotated[ - Optional[str], pydantic.Field(alias="sourceModifiedDate") - ] = None - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "id", - "supplierName", - "contactName", - "emailAddress", - "phone", - "addresses", - "status", - "balance", - "defaultCurrency", - "sourceModifiedDate", - ] - ) - nullable_fields = set( - [ - "contactName", - "emailAddress", - "phone", - "addresses", - "balance", - "defaultCurrency", - ] - ) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - Supplier.model_rebuild() -except NameError: - pass + +class SupplierTypedDict(TypedDict): + """TypedDict variant of Supplier, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + supplier_name: NotRequired[Optional[str]] + contact_name: NotRequired[Optional[str]] + email_address: NotRequired[Optional[str]] + phone: NotRequired[Optional[str]] + addresses: NotRequired[Optional[List[AddressTypedDict]]] + status: NotRequired[Optional[SupplierStatus]] + balance: NotRequired[Optional[Decimal]] + default_currency: NotRequired[Optional[str]] + source_modified_date: NotRequired[Optional[str]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/supplierprototype.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/supplierprototype.py index 3f3ab6aba..5bf6c51ba 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/supplierprototype.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/supplierprototype.py @@ -1,124 +1,136 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .address import Address, AddressTypedDict -from .supplierstatus import SupplierStatus -from codat_sync_for_payables.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from codat_sync_for_payables.utils import serialize_decimal, validate_decimal -from decimal import Decimal -import pydantic -from pydantic import model_serializer -from pydantic.functional_serializers import PlainSerializer -from pydantic.functional_validators import BeforeValidator -from typing import List -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Bill pay (synchronous solution) + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | -class SupplierPrototypeTypedDict(TypedDict): - supplier_name: str - r"""Name of the supplier as recorded in the accounting system, typically the company name.""" - status: SupplierStatus - r"""Status of the supplier.""" - contact_name: NotRequired[Nullable[str]] - r"""Name of the main contact for the supplier.""" - email_address: NotRequired[Nullable[str]] - r"""Email address that the supplier may be contacted on.""" - phone: NotRequired[Nullable[str]] - r"""Phone number that the supplier may be contacted on.""" - addresses: NotRequired[Nullable[List[AddressTypedDict]]] - r"""An array of Addresses.""" - balance: NotRequired[Nullable[Decimal]] - r"""Amount outstanding against the supplier.""" - default_currency: NotRequired[Nullable[str]] - r"""Default currency the supplier's transactional data is recorded in.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 +from __future__ import annotations +from decimal import Decimal +from codat_sync_for_payables.utils.serializers import serialize_decimal, validate_decimal +import pprint +import re # noqa: F401 +import json + +from pydantic import BeforeValidator, PlainSerializer, BaseModel, ConfigDict, Field, model_serializer +from typing import Annotated, Any, ClassVar, Dict, List, Optional, Union +from codat_sync_for_payables.models.shared.address import Address, AddressTypedDict +from codat_sync_for_payables.models.shared.supplierstatus import SupplierStatus +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_sync_for_payables.types import OptionalNullable, UNSET, UNSET_SENTINEL class SupplierPrototype(BaseModel): - supplier_name: Annotated[str, pydantic.Field(alias="supplierName")] - r"""Name of the supplier as recorded in the accounting system, typically the company name.""" + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'addresses', 'balance', 'contactName', 'contact_name', 'defaultCurrency', 'default_currency', 'emailAddress', 'email_address', 'phone'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + SupplierPrototype + """ # noqa: E501 + supplier_name: str = Field(description="Name of the supplier as recorded in the accounting system, typically the company name.", alias="supplierName") + contact_name: OptionalNullable[str] = Field(default=UNSET, description="Name of the main contact for the supplier.", alias="contactName") + email_address: OptionalNullable[str] = Field(default=UNSET, description="Email address that the supplier may be contacted on.", alias="emailAddress") + phone: OptionalNullable[str] = Field(default=UNSET, description="Phone number that the supplier may be contacted on.") + addresses: OptionalNullable[List[Address]] = Field(default=UNSET, description="An array of Addresses.") status: SupplierStatus - r"""Status of the supplier.""" + balance: Annotated[OptionalNullable[Decimal], BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(default=UNSET, description="Amount outstanding against the supplier.") + default_currency: OptionalNullable[str] = Field(default=UNSET, description="Default currency the supplier's transactional data is recorded in.", alias="defaultCurrency") + __properties: ClassVar[List[str]] = ["supplierName", "contactName", "emailAddress", "phone", "addresses", "status", "balance", "defaultCurrency"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of SupplierPrototype from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in addresses (list) + _items = [] + if self.addresses: + for _item_addresses in self.addresses: + if _item_addresses: + _items.append(_item_addresses.to_dict()) + _dict['addresses'] = _items + return _dict - contact_name: Annotated[ - OptionalNullable[str], pydantic.Field(alias="contactName") - ] = UNSET - r"""Name of the main contact for the supplier.""" + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of SupplierPrototype from a dict""" + if obj is None: + return None - email_address: Annotated[ - OptionalNullable[str], pydantic.Field(alias="emailAddress") - ] = UNSET - r"""Email address that the supplier may be contacted on.""" + if not isinstance(obj, dict): + return cls.model_validate(obj) - phone: OptionalNullable[str] = UNSET - r"""Phone number that the supplier may be contacted on.""" + _obj = cls.model_validate({ + "supplierName": obj.get("supplierName"), + "contactName": obj.get("contactName"), + "emailAddress": obj.get("emailAddress"), + "phone": obj.get("phone"), + "addresses": [Address.from_dict(_item) for _item in obj["addresses"]] if obj.get("addresses") is not None else None, + "status": obj.get("status"), + "balance": obj.get("balance"), + "defaultCurrency": obj.get("defaultCurrency") + }) + return _obj - addresses: OptionalNullable[List[Address]] = UNSET - r"""An array of Addresses.""" - balance: Annotated[ - OptionalNullable[Decimal], - BeforeValidator(validate_decimal), - PlainSerializer(serialize_decimal(False)), - ] = UNSET - r"""Amount outstanding against the supplier.""" - default_currency: Annotated[ - OptionalNullable[str], pydantic.Field(alias="defaultCurrency") - ] = UNSET - r"""Default currency the supplier's transactional data is recorded in.""" - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "contactName", - "emailAddress", - "phone", - "addresses", - "balance", - "defaultCurrency", - ] - ) - nullable_fields = set( - [ - "contactName", - "emailAddress", - "phone", - "addresses", - "balance", - "defaultCurrency", - ] - ) - serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - SupplierPrototype.model_rebuild() -except NameError: - pass + +class SupplierPrototypeTypedDict(TypedDict): + """TypedDict variant of SupplierPrototype, for dict-literal request/response inputs.""" + supplier_name: NotRequired[str] + contact_name: NotRequired[Optional[str]] + email_address: NotRequired[Optional[str]] + phone: NotRequired[Optional[str]] + addresses: NotRequired[Optional[List[AddressTypedDict]]] + status: SupplierStatus + balance: NotRequired[Optional[Decimal]] + default_currency: NotRequired[Optional[str]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/supplierref.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/supplierref.py index cce2125db..c02430d1b 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/supplierref.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/supplierref.py @@ -1,65 +1,108 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_payables.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Bill pay (synchronous solution) + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | -class SupplierRefTypedDict(TypedDict): - r"""Reference to the supplier the record relates to.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - id: str - r"""The supplier's unique ID""" - supplier_name: NotRequired[Nullable[str]] - r"""The supplier's name""" + Do not edit the class manually. +""" # noqa: E501 -class SupplierRef(BaseModel): - r"""Reference to the supplier the record relates to.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - id: str - r"""The supplier's unique ID""" +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing_extensions import Annotated, NotRequired, TypedDict +from typing import Optional, Set +from typing_extensions import Self - supplier_name: Annotated[ - OptionalNullable[str], pydantic.Field(alias="supplierName") - ] = UNSET - r"""The supplier's name""" +from codat_sync_for_payables.types import OptionalNullable, UNSET, UNSET_SENTINEL +class SupplierRef(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["supplierName"]) - nullable_fields = set(["supplierName"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - SupplierRef.model_rebuild() -except NameError: - pass + _nullable = {'supplierName', 'supplier_name'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + Reference to the supplier the record relates to. + """ # noqa: E501 + id: str = Field(description="The supplier's unique ID") + supplier_name: OptionalNullable[str] = Field(default=UNSET, description="The supplier's name", alias="supplierName") + __properties: ClassVar[List[str]] = ["id", "supplierName"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of SupplierRef from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of SupplierRef from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "supplierName": obj.get("supplierName") + }) + return _obj + + + + + +class SupplierRefTypedDict(TypedDict): + """TypedDict variant of SupplierRef, for dict-literal request/response inputs.""" + id: NotRequired[str] + supplier_name: NotRequired[Optional[str]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/suppliers.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/suppliers.py index 6b57a2aa4..7adfa40a8 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/suppliers.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/suppliers.py @@ -1,36 +1,114 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .pagination import Pagination, PaginationTypedDict -from .supplier import Supplier, SupplierTypedDict -from codat_sync_for_payables.types import BaseModel, UNSET_SENTINEL -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import NotRequired, TypedDict +""" + Bill pay (synchronous solution) + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | -class SuppliersTypedDict(TypedDict): - results: NotRequired[List[SupplierTypedDict]] - pagination: NotRequired[PaginationTypedDict] + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class Suppliers(BaseModel): - results: Optional[List[Supplier]] = None - pagination: Optional[Pagination] = None +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_sync_for_payables.models.shared.pagination import Pagination, PaginationTypedDict +from codat_sync_for_payables.models.shared.supplier import Supplier, SupplierTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class Suppliers(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["results", "pagination"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + Suppliers + """ # noqa: E501 + results: Optional[List[Supplier]] = None + pagination: Optional[Pagination] = None + __properties: ClassVar[List[str]] = ["results", "pagination"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - return m + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Suppliers from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in results (list) + _items = [] + if self.results: + for _item_results in self.results: + if _item_results: + _items.append(_item_results.to_dict()) + _dict['results'] = _items + # override the default output from pydantic by calling `to_dict()` of pagination + if self.pagination: + _dict['pagination'] = self.pagination.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Suppliers from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "results": [Supplier.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None, + "pagination": Pagination.from_dict(obj["pagination"]) if obj.get("pagination") is not None else None + }) + return _obj + + + + + +class SuppliersTypedDict(TypedDict): + """TypedDict variant of Suppliers, for dict-literal request/response inputs.""" + results: NotRequired[Optional[List[SupplierTypedDict]]] + pagination: NotRequired[Optional[PaginationTypedDict]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/supplierstatus.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/supplierstatus.py index 0f7785837..3c2314a17 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/supplierstatus.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/supplierstatus.py @@ -1,12 +1,39 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations +import json from enum import Enum +from typing_extensions import Self class SupplierStatus(str, Enum): - r"""Status of the supplier.""" + """ + Status of the supplier. + """ + + """ + allowed enum values + """ + UNKNOWN = 'Unknown' + ACTIVE = 'Active' + ARCHIVED = 'Archived' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of SupplierStatus from a JSON string""" + return cls(json.loads(json_str)) + - UNKNOWN = "Unknown" - ACTIVE = "Active" - ARCHIVED = "Archived" diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/taxratemappingoption.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/taxratemappingoption.py index 95ae15ef4..eeab39ff0 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/taxratemappingoption.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/taxratemappingoption.py @@ -1,117 +1,132 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_payables.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from codat_sync_for_payables.utils import serialize_decimal, validate_decimal -from decimal import Decimal -from enum import Enum -import pydantic -from pydantic import model_serializer -from pydantic.functional_serializers import PlainSerializer -from pydantic.functional_validators import BeforeValidator -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class TaxRateStatus(str, Enum): - r"""Status of the tax rate in the accounting software. - - `Active` - An active tax rate in use by a company. - - `Archived` - A tax rate that has been archived or is inactive in the accounting software. - """ +""" + Bill pay (synchronous solution) - ACTIVE = "Active" - ARCHIVED = "Archived" + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) -class TaxRateMappingOptionTypedDict(TypedDict): - id: NotRequired[str] - r"""Identifier for the tax rate, unique for the company in the accounting software.""" - name: NotRequired[Nullable[str]] - r"""Codat-augmented name of the tax rate in the accounting software.""" - code: NotRequired[Nullable[str]] - r"""Code for the tax rate from the accounting software.""" - effective_tax_rate: NotRequired[Nullable[Decimal]] - r"""See Effective tax rates description.""" - total_tax_rate: NotRequired[Nullable[Decimal]] - r"""Total (not compounded) sum of the components of a tax rate.""" - status: NotRequired[TaxRateStatus] - r"""Status of the tax rate in the accounting software. - - `Active` - An active tax rate in use by a company. - - `Archived` - A tax rate that has been archived or is inactive in the accounting software. - """ + Do not edit the class manually. +""" # noqa: E501 +from __future__ import annotations +from decimal import Decimal +from codat_sync_for_payables.utils.serializers import serialize_decimal, validate_decimal +from codat_sync_for_payables.models.tax_rate_status import TaxRateStatus +import pprint +import re # noqa: F401 +import json + +from pydantic import BeforeValidator, PlainSerializer, BaseModel, ConfigDict, Field, field_validator, model_serializer +from typing import Annotated, Any, ClassVar, Dict, List, Optional, Union +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_sync_for_payables.types import OptionalNullable, UNSET, UNSET_SENTINEL class TaxRateMappingOption(BaseModel): - id: Optional[str] = None - r"""Identifier for the tax rate, unique for the company in the accounting software.""" - - name: OptionalNullable[str] = UNSET - r"""Codat-augmented name of the tax rate in the accounting software.""" - - code: OptionalNullable[str] = UNSET - r"""Code for the tax rate from the accounting software.""" - - effective_tax_rate: Annotated[ - Annotated[ - OptionalNullable[Decimal], - BeforeValidator(validate_decimal), - PlainSerializer(serialize_decimal(False)), - ], - pydantic.Field(alias="effectiveTaxRate"), - ] = UNSET - r"""See Effective tax rates description.""" - - total_tax_rate: Annotated[ - Annotated[ - OptionalNullable[Decimal], - BeforeValidator(validate_decimal), - PlainSerializer(serialize_decimal(False)), - ], - pydantic.Field(alias="totalTaxRate"), - ] = UNSET - r"""Total (not compounded) sum of the components of a tax rate.""" - - status: Optional[TaxRateStatus] = None - r"""Status of the tax rate in the accounting software. - - `Active` - An active tax rate in use by a company. - - `Archived` - A tax rate that has been archived or is inactive in the accounting software. - """ @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - ["id", "name", "code", "effectiveTaxRate", "totalTaxRate", "status"] - ) - nullable_fields = set(["name", "code", "effectiveTaxRate", "totalTaxRate"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} - - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - is_nullable_and_explicitly_set = ( - k in nullable_fields - and (self.__pydantic_fields_set__.intersection({n})) # pylint: disable=no-member - ) - - if val != UNSET_SENTINEL: - if ( - val is not None - or k not in optional_fields - or is_nullable_and_explicitly_set - ): - m[k] = val - - return m - - -try: - TaxRateMappingOption.model_rebuild() -except NameError: - pass + _nullable = {'code', 'effectiveTaxRate', 'effective_tax_rate', 'name', 'totalTaxRate', 'total_tax_rate'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + TaxRateMappingOption + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Identifier for the tax rate, unique for the company in the accounting software.") + name: OptionalNullable[str] = Field(default=UNSET, description="Codat-augmented name of the tax rate in the accounting software.") + code: OptionalNullable[str] = Field(default=UNSET, description="Code for the tax rate from the accounting software.") + effective_tax_rate: Annotated[OptionalNullable[Decimal], BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(default=UNSET, description="See Effective tax rates description.", alias="effectiveTaxRate") + total_tax_rate: Annotated[OptionalNullable[Decimal], BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(default=UNSET, description="Total (not compounded) sum of the components of a tax rate.", alias="totalTaxRate") + status: Optional[TaxRateStatus] = Field(default=None, description="Status of the tax rate in the accounting software. - `Active` - An active tax rate in use by a company. - `Archived` - A tax rate that has been archived or is inactive in the accounting software. ") + __properties: ClassVar[List[str]] = ["id", "name", "code", "effectiveTaxRate", "totalTaxRate", "status"] + + @field_validator('status') + def status_validate_enum(cls, value): + """Validates the enum""" + if value is None: + return value + + if value not in set(['Active', 'Archived']): + raise ValueError("must be one of enum values ('Active', 'Archived')") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TaxRateMappingOption from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TaxRateMappingOption from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name"), + "code": obj.get("code"), + "effectiveTaxRate": obj.get("effectiveTaxRate"), + "totalTaxRate": obj.get("totalTaxRate"), + "status": obj.get("status") + }) + return _obj + + + + + +class TaxRateMappingOptionTypedDict(TypedDict): + """TypedDict variant of TaxRateMappingOption, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + name: NotRequired[Optional[str]] + code: NotRequired[Optional[str]] + effective_tax_rate: NotRequired[Optional[Decimal]] + total_tax_rate: NotRequired[Optional[Decimal]] + status: NotRequired[Optional[TaxRateStatus]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/shared/trackingref.py b/sync-for-payables/src/codat_sync_for_payables/models/shared/trackingref.py index 61af5cebe..5ba33e5ff 100644 --- a/sync-for-payables/src/codat_sync_for_payables/models/shared/trackingref.py +++ b/sync-for-payables/src/codat_sync_for_payables/models/shared/trackingref.py @@ -1,58 +1,117 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_payables.types import BaseModel, UNSET_SENTINEL -from enum import Enum -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Bill pay (synchronous solution) + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | -class DataType(str, Enum): - r"""The type of the linked reference.""" + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - TRACKING_CATEGORIES = "trackingCategories" - CUSTOMERS = "customers" + Do not edit the class manually. +""" # noqa: E501 -class TrackingRefTypedDict(TypedDict): - id: NotRequired[str] - r"""Unique identifier of the linked tracking category or the unique identifier of the linked customer.""" - data_type: NotRequired[DataType] - r"""The type of the linked reference.""" - is_billable: NotRequired[bool] - r"""If a customer has been set as the trackingRefs.id then this boolean can be used to set whether the line item is billable to the customer or not.""" +from __future__ import annotations +from codat_sync_for_payables.models.bill_data_type import BillDataType +import pprint +import re # noqa: F401 +import json +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict +from codat_sync_for_payables.models.data_type import DataType class TrackingRef(BaseModel): - id: Optional[str] = None - r"""Unique identifier of the linked tracking category or the unique identifier of the linked customer.""" - - data_type: Annotated[Optional[DataType], pydantic.Field(alias="dataType")] = None - r"""The type of the linked reference.""" - - is_billable: Annotated[Optional[bool], pydantic.Field(alias="isBillable")] = None - r"""If a customer has been set as the trackingRefs.id then this boolean can be used to set whether the line item is billable to the customer or not.""" @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["id", "dataType", "isBillable"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + TrackingRef + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Unique identifier of the linked tracking category or the unique identifier of the linked customer.") + data_type: Optional[DataType] = Field(default=None, description="The type of the linked reference.", alias="dataType") + is_billable: Optional[bool] = Field(default=None, description="If a customer has been set as the trackingRefs.id then this boolean can be used to set whether the line item is billable to the customer or not.", alias="isBillable") + __properties: ClassVar[List[str]] = ["id", "dataType", "isBillable"] + + @field_validator('data_type') + def data_type_validate_enum(cls, value): + """Validates the enum""" + if value is None: + return value + + if value not in set(['trackingCategories', 'customers']): + raise ValueError("must be one of enum values ('trackingCategories', 'customers')") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TrackingRef from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TrackingRef from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "dataType": obj.get("dataType"), + "isBillable": obj.get("isBillable") + }) + return _obj - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - return m -try: - TrackingRef.model_rebuild() -except NameError: - pass +class TrackingRefTypedDict(TypedDict): + """TypedDict variant of TrackingRef, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + data_type: NotRequired[Optional[DataType]] + is_billable: NotRequired[Optional[bool]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/source_modified_date.py b/sync-for-payables/src/codat_sync_for_payables/models/source_modified_date.py new file mode 100644 index 000000000..496386217 --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/models/source_modified_date.py @@ -0,0 +1,99 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class SourceModifiedDate(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + SourceModifiedDate + """ # noqa: E501 + source_modified_date: Optional[str] = Field(default=None, description="The date when a record was last modified in the accounting software, usually by the business or a business process. For example, when payments are made against an invoice. It is not populated ([read more](https://docs.codat.io/using-the-api/modified-dates#source-modified-date)) when: - Pulling attachments - The accounting software does not provide modification dates for a data type - A record has been deleted from the source platform and Codat doesn't have a record of when the deletion occurred - A record has been voided. For certain platforms that soft delete records, `isDeleted` metadata is used to identify void records In Codat's data model, dates and times are represented using the ISO 8601 standard.", alias="sourceModifiedDate") + __properties: ClassVar[List[str]] = ["sourceModifiedDate"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of SourceModifiedDate from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of SourceModifiedDate from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "sourceModifiedDate": obj.get("sourceModifiedDate") + }) + return _obj + + + + + +class SourceModifiedDateTypedDict(TypedDict): + """TypedDict variant of SourceModifiedDate, for dict-literal request/response inputs.""" + source_modified_date: NotRequired[Optional[str]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/source_type.py b/sync-for-payables/src/codat_sync_for_payables/models/source_type.py new file mode 100644 index 000000000..f78ddf03d --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/models/source_type.py @@ -0,0 +1,14 @@ +from __future__ import annotations + +from enum import Enum + + +class SourceType(str, Enum): + """SourceType enum (lifted from inline OAS enum).""" + ACCOUNTING = 'Accounting' + BANKING = 'Banking' + BANK_FEED = 'BankFeed' + COMMERCE = 'Commerce' + EXPENSE = 'Expense' + OTHER = 'Other' + UNKNOWN = 'Unknown' diff --git a/sync-for-payables/src/codat_sync_for_payables/models/status.py b/sync-for-payables/src/codat_sync_for_payables/models/status.py new file mode 100644 index 000000000..ee0bceba4 --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/models/status.py @@ -0,0 +1,56 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class Status(str, Enum): + """ + The current status of the dataset. + """ + + """ + allowed enum values + """ + INITIAL = 'Initial' + QUEUED = 'Queued' + FETCHING = 'Fetching' + MAP_QUEUED = 'MapQueued' + MAPPING = 'Mapping' + COMPLETE = 'Complete' + FETCH_ERROR = 'FetchError' + MAP_ERROR = 'MapError' + INTERNAL_ERROR = 'InternalError' + PROCESSING_QUEUED = 'ProcessingQueued' + PROCESSING = 'Processing' + PROCESSING_ERROR = 'ProcessingError' + VALIDATION_QUEUED = 'ValidationQueued' + VALIDATING = 'Validating' + VALIDATION_ERROR = 'ValidationError' + AUTH_ERROR = 'AuthError' + CANCELLED = 'Cancelled' + NOT_SUPPORTED = 'NotSupported' + RATE_LIMIT_ERROR = 'RateLimitError' + PERMISSIONS_ERROR = 'PermissionsError' + PREREQUISITE_NOT_MET = 'PrerequisiteNotMet' + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of Status from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sync-for-payables/src/codat_sync_for_payables/models/tax_rate_status.py b/sync-for-payables/src/codat_sync_for_payables/models/tax_rate_status.py new file mode 100644 index 000000000..b11e02b14 --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/models/tax_rate_status.py @@ -0,0 +1,9 @@ +from __future__ import annotations + +from enum import Enum + + +class TaxRateStatus(str, Enum): + """TaxRateStatus enum (lifted from inline OAS enum).""" + ACTIVE = 'Active' + ARCHIVED = 'Archived' diff --git a/sync-for-payables/src/codat_sync_for_payables/models/update_connection.py b/sync-for-payables/src/codat_sync_for_payables/models/update_connection.py new file mode 100644 index 000000000..700d176f8 --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/models/update_connection.py @@ -0,0 +1,114 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_sync_for_payables.models.shared.dataconnectionstatus import DataConnectionStatus +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class UpdateConnection(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + UpdateConnection + """ # noqa: E501 + status: Optional[DataConnectionStatus] = Field(default=None, description="The current authorization status of the data connection.") + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["status"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of UpdateConnection from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + * Fields in `self.additional_properties` are added to the output dict. + """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of UpdateConnection from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "status": obj.get("status") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + + + + +class UpdateConnectionTypedDict(TypedDict): + """TypedDict variant of UpdateConnection, for dict-literal request/response inputs.""" + status: NotRequired[Optional[DataConnectionStatus]] + additional_properties: NotRequired[Dict[str, Any]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/validation.py b/sync-for-payables/src/codat_sync_for_payables/models/validation.py new file mode 100644 index 000000000..38b2e8fea --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/models/validation.py @@ -0,0 +1,117 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_sync_for_payables.models.validation_item import ValidationItem, ValidationItemTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class Validation(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + A human-readable object describing validation decisions Codat has made when pushing data into the platform. If a push has failed because of validation errors, they will be detailed here. + """ # noqa: E501 + errors: Optional[List[ValidationItem]] = None + warnings: Optional[List[ValidationItem]] = None + __properties: ClassVar[List[str]] = ["errors", "warnings"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Validation from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in errors (list) + _items = [] + if self.errors: + for _item_errors in self.errors: + if _item_errors: + _items.append(_item_errors.to_dict()) + _dict['errors'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in warnings (list) + _items = [] + if self.warnings: + for _item_warnings in self.warnings: + if _item_warnings: + _items.append(_item_warnings.to_dict()) + _dict['warnings'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Validation from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "errors": [ValidationItem.from_dict(_item) for _item in obj["errors"]] if obj.get("errors") is not None else None, + "warnings": [ValidationItem.from_dict(_item) for _item in obj["warnings"]] if obj.get("warnings") is not None else None + }) + return _obj + + + + + +class ValidationTypedDict(TypedDict): + """TypedDict variant of Validation, for dict-literal request/response inputs.""" + errors: NotRequired[Optional[List[ValidationItemTypedDict]]] + warnings: NotRequired[Optional[List[ValidationItemTypedDict]]] diff --git a/sync-for-payables/src/codat_sync_for_payables/models/validation_item.py b/sync-for-payables/src/codat_sync_for_payables/models/validation_item.py new file mode 100644 index 000000000..149ee7aec --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/models/validation_item.py @@ -0,0 +1,119 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class ValidationItem(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + return {k: v for k, v in serialized.items() if v is not None} + """ + ValidationItem + """ # noqa: E501 + item_id: Optional[str] = Field(default=None, description="Unique identifier for a validation item.", alias="itemId") + message: Optional[str] = Field(default=None, description="A message outlining validation item's issue.") + validator_name: Optional[str] = Field(default=None, description="Name of validator.", alias="validatorName") + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["itemId", "message", "validatorName"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ValidationItem from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + * Fields in `self.additional_properties` are added to the output dict. + """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ValidationItem from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "itemId": obj.get("itemId"), + "message": obj.get("message"), + "validatorName": obj.get("validatorName") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + + + + +class ValidationItemTypedDict(TypedDict): + """TypedDict variant of ValidationItem, for dict-literal request/response inputs.""" + item_id: NotRequired[Optional[str]] + message: NotRequired[Optional[str]] + validator_name: NotRequired[Optional[str]] + additional_properties: NotRequired[Dict[str, Any]] diff --git a/sync-for-payables/src/codat_sync_for_payables/py.typed b/sync-for-payables/src/codat_sync_for_payables/py.typed index 3e38f1a92..e69de29bb 100644 --- a/sync-for-payables/src/codat_sync_for_payables/py.typed +++ b/sync-for-payables/src/codat_sync_for_payables/py.typed @@ -1 +0,0 @@ -# Marker file for PEP 561. The package enables type hints. diff --git a/sync-for-payables/src/codat_sync_for_payables/rest.py b/sync-for-payables/src/codat_sync_for_payables/rest.py new file mode 100644 index 000000000..f79fe354b --- /dev/null +++ b/sync-for-payables/src/codat_sync_for_payables/rest.py @@ -0,0 +1,258 @@ +# coding: utf-8 + +""" + Bill pay (synchronous solution) + + The API reference for the synchronous Bill Pay solution. The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) --- ## Supported Integrations | Integration | Supported | |-------------------------------|-----------| | FreeAgent | Yes | | QuickBooks Online | Yes | | Oracle NetSuite | Yes | | Sage Intacct | Yes | | Xero | Yes | | Zoho Books | Yes | --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Company information | View company profile from the source platform. | | Bills | Get, create, and update Bills. | | Bill payments | Get, create, and update Bill payments. | | Suppliers | Get, create, and update Suppliers. | | Bank accounts | Create a bank account for a given company's connection. | + + The version of the OpenAPI document: 3.0.0 + Contact: support@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import io +import json +import re +import ssl + +import urllib3 + +from codat_sync_for_payables.exceptions import ApiException, ApiValueError + +SUPPORTED_SOCKS_PROXIES = {"socks5", "socks5h", "socks4", "socks4a"} +RESTResponseType = urllib3.HTTPResponse + + +def is_socks_proxy_url(url): + if url is None: + return False + split_section = url.split("://") + if len(split_section) < 2: + return False + else: + return split_section[0].lower() in SUPPORTED_SOCKS_PROXIES + + +class RESTResponse(io.IOBase): + + def __init__(self, resp) -> None: + self.response = resp + self.status = resp.status + self.reason = resp.reason + self.data = None + + def read(self): + if self.data is None: + self.data = self.response.data + return self.data + + def getheaders(self): + """Returns a dictionary of the response headers.""" + return self.response.headers + + def getheader(self, name, default=None): + """Returns a given response header.""" + return self.response.headers.get(name, default) + + +class RESTClientObject: + + def __init__(self, configuration) -> None: + # urllib3.PoolManager will pass all kw parameters to connectionpool + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 + # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 + + # cert_reqs + if configuration.verify_ssl: + cert_reqs = ssl.CERT_REQUIRED + else: + cert_reqs = ssl.CERT_NONE + + pool_args = { + "cert_reqs": cert_reqs, + "ca_certs": configuration.ssl_ca_cert, + "cert_file": configuration.cert_file, + "key_file": configuration.key_file, + } + if configuration.assert_hostname is not None: + pool_args['assert_hostname'] = ( + configuration.assert_hostname + ) + + if configuration.retries is not None: + pool_args['retries'] = configuration.retries + + if configuration.tls_server_name: + pool_args['server_hostname'] = configuration.tls_server_name + + + if configuration.socket_options is not None: + pool_args['socket_options'] = configuration.socket_options + + if configuration.connection_pool_maxsize is not None: + pool_args['maxsize'] = configuration.connection_pool_maxsize + + # https pool manager + self.pool_manager: urllib3.PoolManager + + if configuration.proxy: + if is_socks_proxy_url(configuration.proxy): + from urllib3.contrib.socks import SOCKSProxyManager + pool_args["proxy_url"] = configuration.proxy + pool_args["headers"] = configuration.proxy_headers + self.pool_manager = SOCKSProxyManager(**pool_args) + else: + pool_args["proxy_url"] = configuration.proxy + pool_args["proxy_headers"] = configuration.proxy_headers + self.pool_manager = urllib3.ProxyManager(**pool_args) + else: + self.pool_manager = urllib3.PoolManager(**pool_args) + + def request( + self, + method, + url, + headers=None, + body=None, + post_params=None, + _request_timeout=None + ): + """Perform requests. + + :param method: http request method + :param url: http request url + :param headers: http request headers + :param body: request json body, for `application/json` + :param post_params: request post parameters, + `application/x-www-form-urlencoded` + and `multipart/form-data` + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + """ + method = method.upper() + assert method in [ + 'GET', + 'HEAD', + 'DELETE', + 'POST', + 'PUT', + 'PATCH', + 'OPTIONS' + ] + + if post_params and body: + raise ApiValueError( + "body parameter cannot be used with post_params parameter." + ) + + post_params = post_params or {} + headers = headers or {} + + timeout = None + if _request_timeout: + if isinstance(_request_timeout, (int, float)): + timeout = urllib3.Timeout(total=_request_timeout) + elif ( + isinstance(_request_timeout, tuple) + and len(_request_timeout) == 2 + ): + timeout = urllib3.Timeout( + connect=_request_timeout[0], + read=_request_timeout[1] + ) + + try: + # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` + if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: + + # no content type provided or payload is json + content_type = headers.get('Content-Type') + if ( + not content_type + or re.search('json', content_type, re.IGNORECASE) + ): + request_body = None + if body is not None: + request_body = json.dumps(body) + r = self.pool_manager.request( + method, + url, + body=request_body, + timeout=timeout, + headers=headers, + preload_content=False + ) + elif content_type == 'application/x-www-form-urlencoded': + r = self.pool_manager.request( + method, + url, + fields=post_params, + encode_multipart=False, + timeout=timeout, + headers=headers, + preload_content=False + ) + elif content_type == 'multipart/form-data': + # must del headers['Content-Type'], or the correct + # Content-Type which generated by urllib3 will be + # overwritten. + del headers['Content-Type'] + # Ensures that dict objects are serialized + post_params = [(a, json.dumps(b)) if isinstance(b, dict) else (a,b) for a, b in post_params] + r = self.pool_manager.request( + method, + url, + fields=post_params, + encode_multipart=True, + timeout=timeout, + headers=headers, + preload_content=False + ) + # Pass a `string` parameter directly in the body to support + # other content types than JSON when `body` argument is + # provided in serialized form. + elif isinstance(body, str) or isinstance(body, bytes): + r = self.pool_manager.request( + method, + url, + body=body, + timeout=timeout, + headers=headers, + preload_content=False + ) + elif headers['Content-Type'].startswith('text/') and isinstance(body, bool): + request_body = "true" if body else "false" + r = self.pool_manager.request( + method, + url, + body=request_body, + preload_content=False, + timeout=timeout, + headers=headers) + else: + # Cannot generate the request from given parameters + msg = """Cannot prepare a request message for provided + arguments. Please check that your arguments match + declared content type.""" + raise ApiException(status=0, reason=msg) + # For `GET`, `HEAD` + else: + r = self.pool_manager.request( + method, + url, + fields={}, + timeout=timeout, + headers=headers, + preload_content=False + ) + except urllib3.exceptions.SSLError as e: + msg = "\n".join([type(e).__name__, str(e)]) + raise ApiException(status=0, reason=msg) + + return RESTResponse(r) diff --git a/sync-for-payables/src/codat_sync_for_payables/sdk.py b/sync-for-payables/src/codat_sync_for_payables/sdk.py index c83d020e2..998b19c8e 100644 --- a/sync-for-payables/src/codat_sync_for_payables/sdk.py +++ b/sync-for-payables/src/codat_sync_for_payables/sdk.py @@ -1,64 +1,66 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from .basesdk import BaseSDK -from .httpclient import AsyncHttpClient, ClientOwner, HttpClient, close_clients -from .sdkconfiguration import SDKConfiguration -from .utils.logger import Logger, get_default_logger -from .utils.retries import RetryConfig -from codat_sync_for_payables import utils -from codat_sync_for_payables._hooks import SDKHooks -from codat_sync_for_payables.models import shared -from codat_sync_for_payables.types import OptionalNullable, UNSET -import httpx -import importlib -import sys -from typing import Callable, Dict, Optional, TYPE_CHECKING, Union, cast -import weakref +"""Top-level composed client for Bill pay (synchronous solution). + +Generated by pipeline/postprocess_generated.py — do not edit by hand. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Callable, Dict, Mapping, Optional, Union + +from codat_sync_for_payables.api_client import ApiClient +from codat_sync_for_payables.configuration import Configuration +from codat_sync_for_payables._hooks import SDKHooks, attach_hooks_to_api_client +from codat_sync_for_payables.types import UNSET, OptionalNullable +from codat_sync_for_payables.utils.retries import RetryConfig if TYPE_CHECKING: - from codat_sync_for_payables.bank_accounts import BankAccounts - from codat_sync_for_payables.bill_payments import BillPayments - from codat_sync_for_payables.bills import Bills - from codat_sync_for_payables.companies import Companies - from codat_sync_for_payables.company_information import CompanyInformation - from codat_sync_for_payables.connections import Connections - from codat_sync_for_payables.suppliers import Suppliers - - -class CodatSyncPayables(BaseSDK): - r"""Bill pay (synchronous solution): The API reference for the synchronous Bill Pay solution. - - The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. - - [Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) - - --- - ## Supported Integrations - - | Integration | Supported | - |-------------------------------|-----------| - | FreeAgent | Yes | - | QuickBooks Online | Yes | - | Oracle NetSuite | Yes | - | Sage Intacct | Yes | - | Xero | Yes | - | Zoho Books | Yes | - - --- - - ## Endpoints - - | Endpoints | Description | - | :- |:- | - | Companies | Create and manage your SMB users' companies. | - | Connections | Create new and manage existing data connections for a company. | - | Company information | View company profile from the source platform. | - | Bills | Get, create, and update Bills. | - | Bill payments | Get, create, and update Bill payments. | - | Suppliers | Get, create, and update Suppliers. | - | Bank accounts | Create a bank account for a given company's connection. | - - """ + from codat_sync_for_payables.httpclient import AsyncHttpClient, HttpClient + +from codat_sync_for_payables.api.companies import Companies +from codat_sync_for_payables.api.connections import Connections +from codat_sync_for_payables.api.company_information import CompanyInformation +from codat_sync_for_payables.api.bills import Bills +from codat_sync_for_payables.api.bill_payments import BillPayments +from codat_sync_for_payables.api.suppliers import Suppliers +from codat_sync_for_payables.api.bank_accounts import BankAccounts + + +_DEFAULT_TIMEOUT_MS = 5000 + + +class CodatSyncPayables: + r"""Bill pay (synchronous solution): The API reference for the synchronous Bill Pay solution. + +The synchronous Bill Pay solution is an API and a set of supporting tools designed to integrate a bill pay flow into your app as quickly as possible. It's ideal for facilitating essential bill payment processes within your SMB's accounting software. + +[Explore solution](https://docs.codat.io/payables/overview) | [See OpenAPI spec](https://github.com/codatio/oas) + +--- +## Supported Integrations + +| Integration | Supported | +|-------------------------------|-----------| +| FreeAgent | Yes | +| QuickBooks Online | Yes | +| Oracle NetSuite | Yes | +| Sage Intacct | Yes | +| Xero | Yes | +| Zoho Books | Yes | + +--- + +## Endpoints + +| Endpoints | Description | +| :- |:- | +| Companies | Create and manage your SMB users' companies. | +| Connections | Create new and manage existing data connections for a company. | +| Company information | View company profile from the source platform. | +| Bills | Get, create, and update Bills. | +| Bill payments | Get, create, and update Bill payments. | +| Suppliers | Get, create, and update Suppliers. | +| Bank accounts | Create a bank account for a given company's connection. | +""" companies: "Companies" r"""Create and manage your SMB users' companies.""" @@ -74,22 +76,10 @@ class CodatSyncPayables(BaseSDK): r"""Get, create, and update Suppliers.""" bank_accounts: "BankAccounts" r"""Create a bank account for a given company's connection.""" - _sub_sdk_map = { - "companies": ("codat_sync_for_payables.companies", "Companies"), - "connections": ("codat_sync_for_payables.connections", "Connections"), - "company_information": ( - "codat_sync_for_payables.company_information", - "CompanyInformation", - ), - "bills": ("codat_sync_for_payables.bills", "Bills"), - "bill_payments": ("codat_sync_for_payables.bill_payments", "BillPayments"), - "suppliers": ("codat_sync_for_payables.suppliers", "Suppliers"), - "bank_accounts": ("codat_sync_for_payables.bank_accounts", "BankAccounts"), - } def __init__( self, - security: Union[shared.Security, Callable[[], shared.Security]], + security: Optional[Any] = None, server_idx: Optional[int] = None, url_params: Optional[Dict[str, str]] = None, server_url: Optional[str] = None, @@ -97,139 +87,88 @@ def __init__( async_client: Optional[AsyncHttpClient] = None, retry_config: OptionalNullable[RetryConfig] = UNSET, timeout_ms: Optional[int] = None, - debug_logger: Optional[Logger] = None, + debug_logger: Optional[Any] = None, ) -> None: - r"""Instantiates the SDK configuring it with the provided parameters. - - :param security: The security details required for authentication - :param server_idx: The index of the server to use for all methods - :param server_url: The server URL to use for all methods - :param url_params: Parameters to optionally template the server URL with - :param client: The HTTP client to use for all synchronous methods - :param async_client: The Async HTTP client to use for all asynchronous methods - :param retry_config: The retry configuration to use for all supported methods - :param timeout_ms: Optional request timeout applied to each operation in milliseconds - """ - client_supplied = True - if client is None: - client = httpx.Client(follow_redirects=True) - client_supplied = False - - assert issubclass( - type(client), HttpClient - ), "The provided client must implement the HttpClient protocol." - - async_client_supplied = True - if async_client is None: - async_client = httpx.AsyncClient(follow_redirects=True) - async_client_supplied = False - - if debug_logger is None: - debug_logger = get_default_logger() - - assert issubclass( - type(async_client), AsyncHttpClient - ), "The provided async_client must implement the AsyncHttpClient protocol." - - if server_url is not None: - if url_params is not None: - server_url = utils.template_url(server_url, url_params) - - BaseSDK.__init__( - self, - SDKConfiguration( - client=client, - client_supplied=client_supplied, - async_client=async_client, - async_client_supplied=async_client_supplied, - security=security, - server_url=server_url, - server_idx=server_idx, - retry_config=retry_config, - timeout_ms=timeout_ms, - debug_logger=debug_logger, - ), - parent_ref=self, + self._security = security + self._retry_config = retry_config + self._timeout_ms = timeout_ms + self._debug_logger = debug_logger + if async_client is not None: + import warnings as _w + _w.warn( + "the async_client kwarg is accepted for Speakeasy-SDK compatibility " + "but not used: the bare async methods (e.g. .companies.list_async(...)) " + "run the sync stack in a worker thread, where an httpx.AsyncClient " + "cannot be driven safely. Pass client= (an httpx.Client) instead — it " + "carries every request, including the *_async methods.", + stacklevel=2, + ) + + config = Configuration(host=server_url) if server_url else Configuration() + self._api_client = ApiClient(configuration=config) + if client is not None: + from codat_sync_for_payables._httpx_transport import HttpxRestClient + self._api_client.rest_client = HttpxRestClient(client) + try: + from codat_sync_for_payables._version import __user_agent__ as _ua + self._api_client.set_default_header("User-Agent", _ua) + except Exception: + pass + self._hooks = SDKHooks() + attach_hooks_to_api_client( + self._api_client, + self._hooks, + base_url=(server_url or ""), + security_source=security, + auth_headers=[('auth_header', 'Authorization')], ) - hooks = SDKHooks() - - # pylint: disable=protected-access - self.sdk_configuration.__dict__["_hooks"] = hooks - - current_server_url, *_ = self.sdk_configuration.get_server_details() - server_url, self.sdk_configuration.client = hooks.sdk_init( - current_server_url, client - ) - if current_server_url != server_url: - self.sdk_configuration.server_url = server_url - - weakref.finalize( - self, - close_clients, - cast(ClientOwner, self.sdk_configuration), - self.sdk_configuration.client, - self.sdk_configuration.client_supplied, - self.sdk_configuration.async_client, - self.sdk_configuration.async_client_supplied, - ) - - def dynamic_import(self, modname, retries=3): - for attempt in range(retries): - try: - return importlib.import_module(modname) - except KeyError: - # Clear any half-initialized module and retry - sys.modules.pop(modname, None) - if attempt == retries - 1: - break - raise KeyError(f"Failed to import module '{modname}' after {retries} attempts") - - def __getattr__(self, name: str): - if name in self._sub_sdk_map: - module_path, class_name = self._sub_sdk_map[name] - try: - module = self.dynamic_import(module_path) - klass = getattr(module, class_name) - instance = klass(self.sdk_configuration, parent_ref=self) - setattr(self, name, instance) - return instance - except ImportError as e: - raise AttributeError( - f"Failed to import module {module_path} for attribute {name}: {e}" - ) from e - except AttributeError as e: - raise AttributeError( - f"Failed to find class {class_name} in module {module_path} for attribute {name}: {e}" - ) from e - - raise AttributeError( - f"'{type(self).__name__}' object has no attribute '{name}'" - ) - - def __dir__(self): - default_attrs = list(super().__dir__()) - lazy_attrs = list(self._sub_sdk_map.keys()) - return sorted(list(set(default_attrs + lazy_attrs))) + self.companies = Companies(api_client=self._api_client) + self.connections = Connections(api_client=self._api_client) + self.company_information = CompanyInformation(api_client=self._api_client) + self.bills = Bills(api_client=self._api_client) + self.bill_payments = BillPayments(api_client=self._api_client) + self.suppliers = Suppliers(api_client=self._api_client) + self.bank_accounts = BankAccounts(api_client=self._api_client) + + # Attach the SDK-level retry + timeout defaults to each method-group so a + # per-call retries=UNSET / timeout_ms=None falls back to them. When no + # timeout_ms is set the default is _DEFAULT_TIMEOUT_MS (matches the shipped SDK). + _sdk_retry_default = retry_config if not isinstance(retry_config, type(UNSET)) else None + _sdk_timeout_default = timeout_ms if timeout_ms is not None else _DEFAULT_TIMEOUT_MS + _group_api_prefix = type(self).__module__.rsplit(".", 1)[0] + ".api." + _defaults_seen: set = set() + + def _attach_sdk_defaults(_grp) -> None: + if id(_grp) in _defaults_seen: + return + _defaults_seen.add(id(_grp)) + object.__setattr__(_grp, "_sdk_retry_config", _sdk_retry_default) + object.__setattr__(_grp, "_sdk_timeout_ms", _sdk_timeout_default) + for _name, _child in list(vars(_grp).items()): + if not _name.startswith("_") and type(_child).__module__.startswith(_group_api_prefix): + _attach_sdk_defaults(_child) + + for _grp in ( + self.companies, + self.connections, + self.company_information, + self.bills, + self.bill_payments, + self.suppliers, + self.bank_accounts, + ): + _attach_sdk_defaults(_grp) - def __enter__(self): + def __enter__(self) -> "CodatSyncPayables": + self._api_client.__enter__() return self - async def __aenter__(self): - return self + def __exit__(self, exc_type, exc, tb) -> None: + self._api_client.__exit__(exc_type, exc, tb) - def __exit__(self, exc_type, exc_val, exc_tb): - if ( - self.sdk_configuration.client is not None - and not self.sdk_configuration.client_supplied - ): - self.sdk_configuration.client.close() - self.sdk_configuration.client = None + async def __aenter__(self) -> "CodatSyncPayables": + return self - async def __aexit__(self, exc_type, exc_val, exc_tb): - if ( - self.sdk_configuration.async_client is not None - and not self.sdk_configuration.async_client_supplied - ): - await self.sdk_configuration.async_client.aclose() - self.sdk_configuration.async_client = None + async def __aexit__(self, exc_type, exc, tb) -> None: + self._api_client.__exit__(exc_type, exc, tb) diff --git a/sync-for-payables/src/codat_sync_for_payables/sdkconfiguration.py b/sync-for-payables/src/codat_sync_for_payables/sdkconfiguration.py deleted file mode 100644 index 49269e53b..000000000 --- a/sync-for-payables/src/codat_sync_for_payables/sdkconfiguration.py +++ /dev/null @@ -1,49 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from ._version import ( - __gen_version__, - __openapi_doc_version__, - __user_agent__, - __version__, -) -from .httpclient import AsyncHttpClient, HttpClient -from .utils import Logger, RetryConfig, remove_suffix -from codat_sync_for_payables.models import shared -from codat_sync_for_payables.types import OptionalNullable, UNSET -from dataclasses import dataclass -from pydantic import Field -from typing import Callable, Dict, Optional, Tuple, Union - - -SERVERS = [ - "https://api.codat.io", - # Production -] -"""Contains the list of servers available to the SDK""" - - -@dataclass -class SDKConfiguration: - client: Union[HttpClient, None] - client_supplied: bool - async_client: Union[AsyncHttpClient, None] - async_client_supplied: bool - debug_logger: Logger - security: Optional[Union[shared.Security, Callable[[], shared.Security]]] = None - server_url: Optional[str] = "" - server_idx: Optional[int] = 0 - language: str = "python" - openapi_doc_version: str = __openapi_doc_version__ - sdk_version: str = __version__ - gen_version: str = __gen_version__ - user_agent: str = __user_agent__ - retry_config: OptionalNullable[RetryConfig] = Field(default_factory=lambda: UNSET) - timeout_ms: Optional[int] = None - - def get_server_details(self) -> Tuple[str, Dict[str, str]]: - if self.server_url is not None and self.server_url: - return remove_suffix(self.server_url, "/"), {} - if self.server_idx is None: - self.server_idx = 0 - - return SERVERS[self.server_idx], {} diff --git a/sync-for-payables/src/codat_sync_for_payables/suppliers.py b/sync-for-payables/src/codat_sync_for_payables/suppliers.py index 81ffdd371..fae34f725 100644 --- a/sync-for-payables/src/codat_sync_for_payables/suppliers.py +++ b/sync-for-payables/src/codat_sync_for_payables/suppliers.py @@ -1,733 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.suppliers — re-export of the suppliers method group.""" -from .basesdk import BaseSDK -from codat_sync_for_payables import utils -from codat_sync_for_payables._hooks import HookContext -from codat_sync_for_payables.models import errors, operations, shared -from codat_sync_for_payables.types import BaseModel, OptionalNullable, UNSET -from codat_sync_for_payables.utils.unmarshal_json_response import ( - unmarshal_json_response, -) -from typing import Any, Mapping, Optional, Union, cast - - -class Suppliers(BaseSDK): - r"""Get, create, and update Suppliers.""" - - def list( - self, - *, - request: Union[ - operations.ListSuppliersRequest, operations.ListSuppliersRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Suppliers: - r"""List suppliers - - The *List suppliers* endpoint returns a list of [suppliers](https://docs.codat.io/sync-for-payables-api#/schemas/Supplier) for a given company's connection. - - [Suppliers](https://docs.codat.io/sync-for-payables-api#/schemas/Supplier) are people or organizations that provide something, such as a product or service. - - By default, this endpoint returns a list of active and archived suppliers. You can use [querying](https://docs.codat.io/using-the-api/querying) to change that. - - For example, to retrieve only active suppliers (i.e. `status=Active`) or suppliers created within the specified number of days (e.g. `sourceModifiedDate>2023-12-15T00:00:00.000Z`), query the endpoint as follows: `/payables/suppliers?query=sourceModifiedDate>2023-12-15T00:00:00.000Z&&status=Active`.For example, to retrieve active suppliers modified after a particular date use `query=sourceModifiedDate>2023-12-15T00:00:00.000Z&&status=Active`. - - ### Supported Integrations - - | Integration | Supported | - |-------------------------------|-----------| - | FreeAgent | Yes | - | QuickBooks Online | Yes | - | Xero | Yes | - | Oracle NetSuite | Yes | - | Sage Intacct | Yes | - | Zoho Books | Yes | - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.ListSuppliersRequest) - request = cast(operations.ListSuppliersRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/connections/{connectionId}/payables/suppliers", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="list-suppliers", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Suppliers, http_res) - if utils.match_response( - http_res, - ["400", "401", "402", "403", "404", "409", "429"], - "application/json", - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def list_async( - self, - *, - request: Union[ - operations.ListSuppliersRequest, operations.ListSuppliersRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Suppliers: - r"""List suppliers - - The *List suppliers* endpoint returns a list of [suppliers](https://docs.codat.io/sync-for-payables-api#/schemas/Supplier) for a given company's connection. - - [Suppliers](https://docs.codat.io/sync-for-payables-api#/schemas/Supplier) are people or organizations that provide something, such as a product or service. - - By default, this endpoint returns a list of active and archived suppliers. You can use [querying](https://docs.codat.io/using-the-api/querying) to change that. - - For example, to retrieve only active suppliers (i.e. `status=Active`) or suppliers created within the specified number of days (e.g. `sourceModifiedDate>2023-12-15T00:00:00.000Z`), query the endpoint as follows: `/payables/suppliers?query=sourceModifiedDate>2023-12-15T00:00:00.000Z&&status=Active`.For example, to retrieve active suppliers modified after a particular date use `query=sourceModifiedDate>2023-12-15T00:00:00.000Z&&status=Active`. - - ### Supported Integrations - - | Integration | Supported | - |-------------------------------|-----------| - | FreeAgent | Yes | - | QuickBooks Online | Yes | - | Xero | Yes | - | Oracle NetSuite | Yes | - | Sage Intacct | Yes | - | Zoho Books | Yes | - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.ListSuppliersRequest) - request = cast(operations.ListSuppliersRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/connections/{connectionId}/payables/suppliers", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="list-suppliers", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Suppliers, http_res) - if utils.match_response( - http_res, - ["400", "401", "402", "403", "404", "409", "429"], - "application/json", - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def create( - self, - *, - request: Union[ - operations.CreateSupplierRequest, operations.CreateSupplierRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Supplier: - r"""Create supplier - - The *Create supplier* endpoint creates a new [supplier](https://docs.codat.io/sync-for-payables-api#/schemas/Supplier) for a given company's connection. - - [Suppliers](https://docs.codat.io/sync-for-payables-api#/schemas/Supplier) are people or organizations that provide something, such as a product or service. - - ### Supported Integrations - - | Integration | Supported | - |-------------------------------|-----------| - | FreeAgent | Yes | - | QuickBooks Online | Yes | - | Xero | Yes | - | Oracle NetSuite | Yes | - | Sage Intacct | Yes | - | Zoho Books | Yes | - - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.CreateSupplierRequest) - request = cast(operations.CreateSupplierRequest, request) - - req = self._build_request( - method="POST", - path="/companies/{companyId}/connections/{connectionId}/payables/suppliers", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.supplier_prototype if request is not None else None, - False, - True, - "json", - Optional[shared.SupplierPrototype], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="create-supplier", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "201", "application/json"): - return unmarshal_json_response(shared.Supplier, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def create_async( - self, - *, - request: Union[ - operations.CreateSupplierRequest, operations.CreateSupplierRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Supplier: - r"""Create supplier - - The *Create supplier* endpoint creates a new [supplier](https://docs.codat.io/sync-for-payables-api#/schemas/Supplier) for a given company's connection. - - [Suppliers](https://docs.codat.io/sync-for-payables-api#/schemas/Supplier) are people or organizations that provide something, such as a product or service. - - ### Supported Integrations - - | Integration | Supported | - |-------------------------------|-----------| - | FreeAgent | Yes | - | QuickBooks Online | Yes | - | Xero | Yes | - | Oracle NetSuite | Yes | - | Sage Intacct | Yes | - | Zoho Books | Yes | - - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.CreateSupplierRequest) - request = cast(operations.CreateSupplierRequest, request) - - req = self._build_request_async( - method="POST", - path="/companies/{companyId}/connections/{connectionId}/payables/suppliers", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.supplier_prototype if request is not None else None, - False, - True, - "json", - Optional[shared.SupplierPrototype], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="create-supplier", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "201", "application/json"): - return unmarshal_json_response(shared.Supplier, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - def update( - self, - *, - request: Union[ - operations.UpdateSupplierRequest, operations.UpdateSupplierRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Supplier: - r"""Update supplier - - The *Update supplier* endpoint updates an existing [supplier](https://docs.codat.io/sync-for-payables-api#/schemas/Supplier) for a given company's connection. - - [Suppliers](https://docs.codat.io/sync-for-payables-api#/schemas/Supplier) are people or organizations that provide something, such as a product or service. - - This is a full-replace PUT endpoint. Any fields not included in the request body will be cleared on the supplier record. - - ### Supported Integrations - - | Integration | Supported | - |-------------------------------|-----------| - | FreeAgent | Yes | - | QuickBooks Online | Yes | - | Xero | Yes | - | Oracle NetSuite | No | - | Sage Intacct | No | - | Zoho Books | No | - - ### Platform-specific behavior - - - **Xero**: Archived suppliers cannot be updated (returns `400`). Suppliers must be unarchived manually in the Xero UI before updating. - - **QuickBooks Online**: Currency can only be set when creating a supplier, and cannot be changed via update. - - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.UpdateSupplierRequest) - request = cast(operations.UpdateSupplierRequest, request) - - req = self._build_request( - method="PUT", - path="/companies/{companyId}/connections/{connectionId}/payables/suppliers/{supplierId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.supplier_prototype if request is not None else None, - False, - True, - "json", - Optional[shared.SupplierPrototype], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = self.do_request( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="update-supplier", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Supplier, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = utils.stream_to_text(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) - - async def update_async( - self, - *, - request: Union[ - operations.UpdateSupplierRequest, operations.UpdateSupplierRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Supplier: - r"""Update supplier - - The *Update supplier* endpoint updates an existing [supplier](https://docs.codat.io/sync-for-payables-api#/schemas/Supplier) for a given company's connection. - - [Suppliers](https://docs.codat.io/sync-for-payables-api#/schemas/Supplier) are people or organizations that provide something, such as a product or service. - - This is a full-replace PUT endpoint. Any fields not included in the request body will be cleared on the supplier record. - - ### Supported Integrations - - | Integration | Supported | - |-------------------------------|-----------| - | FreeAgent | Yes | - | QuickBooks Online | Yes | - | Xero | Yes | - | Oracle NetSuite | No | - | Sage Intacct | No | - | Zoho Books | No | - - ### Platform-specific behavior - - - **Xero**: Archived suppliers cannot be updated (returns `400`). Suppliers must be unarchived manually in the Xero UI before updating. - - **QuickBooks Online**: Currency can only be set when creating a supplier, and cannot be changed via update. - - - :param request: The request object to send. - :param retries: Override the default retry configuration for this method - :param server_url: Override the default server URL for this method - :param timeout_ms: Override the default request timeout configuration for this method in milliseconds - :param http_headers: Additional headers to set or replace on requests. - """ - base_url = None - url_variables = None - if timeout_ms is None: - timeout_ms = self.sdk_configuration.timeout_ms - - if server_url is not None: - base_url = server_url - else: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal(request, operations.UpdateSupplierRequest) - request = cast(operations.UpdateSupplierRequest, request) - - req = self._build_request_async( - method="PUT", - path="/companies/{companyId}/connections/{connectionId}/payables/suppliers/{supplierId}", - base_url=base_url, - url_variables=url_variables, - request=request, - request_body_required=False, - request_has_path_params=True, - request_has_query_params=True, - user_agent_header="user-agent", - accept_header_value="application/json", - http_headers=http_headers, - security=self.sdk_configuration.security, - get_serialized_body=lambda: utils.serialize_request_body( - request.supplier_prototype if request is not None else None, - False, - True, - "json", - Optional[shared.SupplierPrototype], - ), - allow_empty_value=None, - timeout_ms=timeout_ms, - ) - - if retries == UNSET: - if self.sdk_configuration.retry_config is not UNSET: - retries = self.sdk_configuration.retry_config - else: - retries = utils.RetryConfig( - "backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True - ) - - retry_config = None - if isinstance(retries, utils.RetryConfig): - retry_config = (retries, ["408", "429", "5XX"]) - - http_res = await self.do_request_async( - hook_ctx=HookContext( - config=self.sdk_configuration, - base_url=base_url or "", - operation_id="update-supplier", - oauth2_scopes=None, - security_source=self.sdk_configuration.security, - ), - request=req, - is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), - retry_config=retry_config, - ) - - response_data: Any = None - if utils.match_response(http_res, "200", "application/json"): - return unmarshal_json_response(shared.Supplier, http_res) - if utils.match_response( - http_res, ["400", "401", "402", "403", "404", "429"], "application/json" - ): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, ["500", "503"], "application/json"): - response_data = unmarshal_json_response(errors.ErrorMessageData, http_res) - raise errors.ErrorMessage(response_data, http_res) - if utils.match_response(http_res, "4XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - if utils.match_response(http_res, "5XX", "*"): - http_res_text = await utils.stream_to_text_async(http_res) - raise errors.SDKError("API error occurred", http_res, http_res_text) - - raise errors.SDKError("Unexpected response received", http_res) +from codat_sync_for_payables.api.suppliers import Suppliers diff --git a/sync-for-payables/src/codat_sync_for_payables/types/__init__.py b/sync-for-payables/src/codat_sync_for_payables/types/__init__.py index faa268137..a5e7b8709 100644 --- a/sync-for-payables/src/codat_sync_for_payables/types/__init__.py +++ b/sync-for-payables/src/codat_sync_for_payables/types/__init__.py @@ -1,24 +1,52 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from .base64fileinput import Base64EncodedString, Base64FileInput -from .basemodel import ( - BaseModel, - Nullable, - OptionalNullable, - UnrecognizedInt, - UnrecognizedStr, - UNSET, - UNSET_SENTINEL, -) - -__all__ = [ - "Base64EncodedString", - "Base64FileInput", - "BaseModel", - "Nullable", - "OptionalNullable", - "UnrecognizedInt", - "UnrecognizedStr", - "UNSET", - "UNSET_SENTINEL", -] +"""Sentinel / type-alias helpers — matches Speakeasy SDK surface.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Optional, TypeVar, Union +from typing_extensions import Literal, TypeAlias, TypeAliasType + +from pydantic import BaseModel as BaseModel, ConfigDict, model_serializer + +# Speakeasy exposes UnrecognizedInt/UnrecognizedStr as the fallback types for open +# (extensible) enums. POC keeps the plain scalar, so these alias to int/str — a +# consumer annotating with them type-checks and runs identically. +UnrecognizedInt: TypeAlias = int +UnrecognizedStr: TypeAlias = str + +UNSET_SENTINEL = "~?~unset~?~sentinel~?~" + + +class Unset(BaseModel): + """Sentinel distinguishing "not provided" (UNSET) from "explicit None". As a + pydantic model it serializes to UNSET_SENTINEL, so a model serializer can drop + UNSET fields from the wire payload while still emitting explicit nulls.""" + + model_config = ConfigDict(arbitrary_types_allowed=True) + + @model_serializer(mode="plain") + def serialize_model(self): + return UNSET_SENTINEL + + def __bool__(self) -> Literal[False]: + return False + + def __repr__(self) -> str: + return "UNSET" + + +UNSET = Unset() +_Unset = Unset # backwards-compat alias for the class name + +T = TypeVar("T") + +if TYPE_CHECKING: + Nullable: TypeAlias = Union[T, None] + OptionalNullable: TypeAlias = Union[Optional[Nullable[T]], _Unset] +else: + Nullable = TypeAliasType("Nullable", Union[T, None], type_params=(T,)) + OptionalNullable = TypeAliasType( + "OptionalNullable", Union[Optional[T], _Unset], type_params=(T,) + ) + + +__all__ = ["BaseModel", "UNSET", "UNSET_SENTINEL", "Unset", "Nullable", "OptionalNullable", "UnrecognizedInt", "UnrecognizedStr"] diff --git a/sync-for-payables/src/codat_sync_for_payables/types/base64fileinput.py b/sync-for-payables/src/codat_sync_for_payables/types/base64fileinput.py deleted file mode 100644 index 25fc53989..000000000 --- a/sync-for-payables/src/codat_sync_for_payables/types/base64fileinput.py +++ /dev/null @@ -1,39 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from __future__ import annotations - -import base64 -import io -from os import PathLike -from typing import IO, Any, Union - -from pydantic.functional_validators import BeforeValidator -from typing_extensions import Annotated - - -Base64FileInput = Union[IO[bytes], PathLike[str]] - - -def encode_base64_file_input(value: Any) -> Any: - """Convert PathLike or IO[bytes] inputs to a base64 string. All standard binary streams - that inherit from io.IOBase are handled. Other values pass through. - """ - if isinstance(value, (PathLike, io.IOBase)): - if isinstance(value, PathLike): - with open(value, "rb") as fh: - binary = fh.read() - else: - binary = value.read() - if isinstance(binary, str): - binary = binary.encode() - if not isinstance(binary, (bytes, bytearray)): - raise TypeError( - f"Base64FileInput expected binary IO returning bytes; got {type(binary).__name__}" - ) - return base64.b64encode(binary).decode("ascii") - return value - - -# Non-str inputs are converted to base64 by the BeforeValidator at construction time. -# Callers can also pass a pre-encoded base64 str. -Base64EncodedString = Annotated[str, BeforeValidator(encode_base64_file_input)] diff --git a/sync-for-payables/src/codat_sync_for_payables/types/basemodel.py b/sync-for-payables/src/codat_sync_for_payables/types/basemodel.py deleted file mode 100644 index a9a640a1a..000000000 --- a/sync-for-payables/src/codat_sync_for_payables/types/basemodel.py +++ /dev/null @@ -1,77 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from pydantic import ConfigDict, model_serializer -from pydantic import BaseModel as PydanticBaseModel -from pydantic_core import core_schema -from typing import TYPE_CHECKING, Any, Literal, Optional, TypeVar, Union -from typing_extensions import TypeAliasType, TypeAlias - - -class BaseModel(PydanticBaseModel): - model_config = ConfigDict( - populate_by_name=True, arbitrary_types_allowed=True, protected_namespaces=() - ) - - -class Unset(BaseModel): - @model_serializer(mode="plain") - def serialize_model(self): - return UNSET_SENTINEL - - def __bool__(self) -> Literal[False]: - return False - - -UNSET = Unset() -UNSET_SENTINEL = "~?~unset~?~sentinel~?~" - - -T = TypeVar("T") -if TYPE_CHECKING: - Nullable: TypeAlias = Union[T, None] - OptionalNullable: TypeAlias = Union[Optional[Nullable[T]], Unset] -else: - Nullable = TypeAliasType("Nullable", Union[T, None], type_params=(T,)) - OptionalNullable = TypeAliasType( - "OptionalNullable", Union[Optional[Nullable[T]], Unset], type_params=(T,) - ) - - -class UnrecognizedStr(str): - @classmethod - def __get_pydantic_core_schema__(cls, _source_type: Any, _handler: Any) -> core_schema.CoreSchema: - # Make UnrecognizedStr only work in lax mode, not strict mode - # This makes it a "fallback" option when more specific types (like Literals) don't match - def validate_lax(v: Any) -> 'UnrecognizedStr': - if isinstance(v, cls): - return v - return cls(str(v)) - - # Use lax_or_strict_schema where strict always fails - # This forces Pydantic to prefer other union members in strict mode - # and only fall back to UnrecognizedStr in lax mode - return core_schema.lax_or_strict_schema( - lax_schema=core_schema.chain_schema([ - core_schema.str_schema(), - core_schema.no_info_plain_validator_function(validate_lax) - ]), - strict_schema=core_schema.none_schema(), # Always fails in strict mode - ) - - -class UnrecognizedInt(int): - @classmethod - def __get_pydantic_core_schema__(cls, _source_type: Any, _handler: Any) -> core_schema.CoreSchema: - # Make UnrecognizedInt only work in lax mode, not strict mode - # This makes it a "fallback" option when more specific types (like Literals) don't match - def validate_lax(v: Any) -> 'UnrecognizedInt': - if isinstance(v, cls): - return v - return cls(int(v)) - return core_schema.lax_or_strict_schema( - lax_schema=core_schema.chain_schema([ - core_schema.int_schema(), - core_schema.no_info_plain_validator_function(validate_lax) - ]), - strict_schema=core_schema.none_schema(), # Always fails in strict mode - ) diff --git a/sync-for-payables/src/codat_sync_for_payables/utils/__init__.py b/sync-for-payables/src/codat_sync_for_payables/utils/__init__.py index 0498cb8da..b0437aac2 100644 --- a/sync-for-payables/src/codat_sync_for_payables/utils/__init__.py +++ b/sync-for-payables/src/codat_sync_for_payables/utils/__init__.py @@ -1,175 +1,5 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_payables.utils — utility helpers (currently retry config).""" -from typing import Any, TYPE_CHECKING, Callable, TypeVar -import asyncio +from .retries import BackoffStrategy, RetryConfig, Retries -from .dynamic_imports import lazy_getattr, lazy_dir - -_T = TypeVar("_T") - - -async def run_sync_in_thread(func: Callable[..., _T], *args) -> _T: - """Run a synchronous function in a thread pool to avoid blocking the event loop.""" - return await asyncio.to_thread(func, *args) - - -if TYPE_CHECKING: - from .annotations import get_discriminator - from .datetimes import parse_datetime - from .enums import OpenEnumMeta - from .headers import get_headers, get_response_headers - from .metadata import ( - FieldMetadata, - find_metadata, - FormMetadata, - HeaderMetadata, - MultipartFormMetadata, - PathParamMetadata, - QueryParamMetadata, - RequestMetadata, - SecurityMetadata, - ) - from .queryparams import get_query_params - from .retries import BackoffStrategy, Retries, retry, retry_async, RetryConfig - from .requestbodies import serialize_request_body, SerializedRequestBody - from .security import get_security - from .serializers import ( - get_pydantic_model, - marshal_json, - unmarshal, - unmarshal_json, - serialize_decimal, - serialize_float, - serialize_int, - stream_to_text, - stream_to_text_async, - stream_to_bytes, - stream_to_bytes_async, - validate_const, - validate_decimal, - validate_float, - validate_int, - ) - from .url import generate_url, template_url, remove_suffix - from .values import ( - get_global_from_env, - match_content_type, - match_status_codes, - match_response, - cast_partial, - ) - from .logger import Logger, get_body_content, get_default_logger - -__all__ = [ - "BackoffStrategy", - "FieldMetadata", - "find_metadata", - "FormMetadata", - "generate_url", - "get_body_content", - "get_default_logger", - "get_discriminator", - "parse_datetime", - "get_global_from_env", - "get_headers", - "get_pydantic_model", - "get_query_params", - "get_response_headers", - "get_security", - "HeaderMetadata", - "Logger", - "marshal_json", - "match_content_type", - "match_status_codes", - "match_response", - "MultipartFormMetadata", - "OpenEnumMeta", - "PathParamMetadata", - "QueryParamMetadata", - "remove_suffix", - "Retries", - "retry", - "retry_async", - "RetryConfig", - "RequestMetadata", - "SecurityMetadata", - "serialize_decimal", - "serialize_float", - "serialize_int", - "serialize_request_body", - "SerializedRequestBody", - "stream_to_text", - "stream_to_text_async", - "stream_to_bytes", - "stream_to_bytes_async", - "template_url", - "unmarshal", - "unmarshal_json", - "validate_decimal", - "validate_const", - "validate_float", - "validate_int", - "cast_partial", -] - -_dynamic_imports: dict[str, str] = { - "BackoffStrategy": ".retries", - "FieldMetadata": ".metadata", - "find_metadata": ".metadata", - "FormMetadata": ".metadata", - "generate_url": ".url", - "get_body_content": ".logger", - "get_default_logger": ".logger", - "get_discriminator": ".annotations", - "parse_datetime": ".datetimes", - "get_global_from_env": ".values", - "get_headers": ".headers", - "get_pydantic_model": ".serializers", - "get_query_params": ".queryparams", - "get_response_headers": ".headers", - "get_security": ".security", - "HeaderMetadata": ".metadata", - "Logger": ".logger", - "marshal_json": ".serializers", - "match_content_type": ".values", - "match_status_codes": ".values", - "match_response": ".values", - "MultipartFormMetadata": ".metadata", - "OpenEnumMeta": ".enums", - "PathParamMetadata": ".metadata", - "QueryParamMetadata": ".metadata", - "remove_suffix": ".url", - "Retries": ".retries", - "retry": ".retries", - "retry_async": ".retries", - "RetryConfig": ".retries", - "RequestMetadata": ".metadata", - "SecurityMetadata": ".metadata", - "serialize_decimal": ".serializers", - "serialize_float": ".serializers", - "serialize_int": ".serializers", - "serialize_request_body": ".requestbodies", - "SerializedRequestBody": ".requestbodies", - "stream_to_text": ".serializers", - "stream_to_text_async": ".serializers", - "stream_to_bytes": ".serializers", - "stream_to_bytes_async": ".serializers", - "template_url": ".url", - "unmarshal": ".serializers", - "unmarshal_json": ".serializers", - "validate_decimal": ".serializers", - "validate_const": ".serializers", - "validate_float": ".serializers", - "validate_int": ".serializers", - "cast_partial": ".values", -} - - -def __getattr__(attr_name: str) -> Any: - return lazy_getattr( - attr_name, package=__package__, dynamic_imports=_dynamic_imports - ) - - -def __dir__(): - return lazy_dir(dynamic_imports=_dynamic_imports) +__all__ = ["BackoffStrategy", "RetryConfig", "Retries"] diff --git a/sync-for-payables/src/codat_sync_for_payables/utils/annotations.py b/sync-for-payables/src/codat_sync_for_payables/utils/annotations.py deleted file mode 100644 index 12e0aa4f1..000000000 --- a/sync-for-payables/src/codat_sync_for_payables/utils/annotations.py +++ /dev/null @@ -1,79 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from enum import Enum -from typing import Any, Optional - - -def get_discriminator(model: Any, fieldname: str, key: str) -> str: - """ - Recursively search for the discriminator attribute in a model. - - Args: - model (Any): The model to search within. - fieldname (str): The name of the field to search for. - key (str): The key to search for in dictionaries. - - Returns: - str: The name of the discriminator attribute. - - Raises: - ValueError: If the discriminator attribute is not found. - """ - upper_fieldname = fieldname.upper() - - def get_field_discriminator(field: Any) -> Optional[str]: - """Search for the discriminator attribute in a given field.""" - - if isinstance(field, dict): - if key in field: - return f"{field[key]}" - - if hasattr(field, fieldname): - attr = getattr(field, fieldname) - if isinstance(attr, Enum): - return f"{attr.value}" - return f"{attr}" - - if hasattr(field, upper_fieldname): - attr = getattr(field, upper_fieldname) - if isinstance(attr, Enum): - return f"{attr.value}" - return f"{attr}" - - return None - - def search_nested_discriminator(obj: Any) -> Optional[str]: - """Recursively search for discriminator in nested structures.""" - # First try direct field lookup - discriminator = get_field_discriminator(obj) - if discriminator is not None: - return discriminator - - # If it's a dict, search in nested values - if isinstance(obj, dict): - for value in obj.values(): - if isinstance(value, list): - # Search in list items - for item in value: - nested_discriminator = search_nested_discriminator(item) - if nested_discriminator is not None: - return nested_discriminator - elif isinstance(value, dict): - # Search in nested dict - nested_discriminator = search_nested_discriminator(value) - if nested_discriminator is not None: - return nested_discriminator - - return None - - if isinstance(model, list): - for field in model: - discriminator = search_nested_discriminator(field) - if discriminator is not None: - return discriminator - - discriminator = search_nested_discriminator(model) - if discriminator is not None: - return discriminator - - raise ValueError(f"Could not find discriminator field {fieldname} in {model}") diff --git a/sync-for-payables/src/codat_sync_for_payables/utils/datetimes.py b/sync-for-payables/src/codat_sync_for_payables/utils/datetimes.py deleted file mode 100644 index a6c52cd61..000000000 --- a/sync-for-payables/src/codat_sync_for_payables/utils/datetimes.py +++ /dev/null @@ -1,23 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from datetime import datetime -import sys - - -def parse_datetime(datetime_string: str) -> datetime: - """ - Convert a RFC 3339 / ISO 8601 formatted string into a datetime object. - Python versions 3.11 and later support parsing RFC 3339 directly with - datetime.fromisoformat(), but for earlier versions, this function - encapsulates the necessary extra logic. - """ - # Python 3.11 and later can parse RFC 3339 directly - if sys.version_info >= (3, 11): - return datetime.fromisoformat(datetime_string) - - # For Python 3.10 and earlier, a common ValueError is trailing 'Z' suffix, - # so fix that upfront. - if datetime_string.endswith("Z"): - datetime_string = datetime_string[:-1] + "+00:00" - - return datetime.fromisoformat(datetime_string) diff --git a/sync-for-payables/src/codat_sync_for_payables/utils/dynamic_imports.py b/sync-for-payables/src/codat_sync_for_payables/utils/dynamic_imports.py deleted file mode 100644 index 673edf82a..000000000 --- a/sync-for-payables/src/codat_sync_for_payables/utils/dynamic_imports.py +++ /dev/null @@ -1,54 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from importlib import import_module -import builtins -import sys - - -def dynamic_import(package, modname, retries=3): - """Import a module relative to package, retrying on KeyError from half-initialized modules.""" - for attempt in range(retries): - try: - return import_module(modname, package) - except KeyError: - sys.modules.pop(modname, None) - if attempt == retries - 1: - break - raise KeyError(f"Failed to import module '{modname}' after {retries} attempts") - - -def lazy_getattr(attr_name, *, package, dynamic_imports, sub_packages=None): - """Module-level __getattr__ that lazily loads from a dynamic_imports mapping. - - Args: - attr_name: The attribute being looked up. - package: The caller's __package__ (for relative imports). - dynamic_imports: Dict mapping attribute names to relative module paths. - sub_packages: Optional list of subpackage names to lazy-load. - """ - module_name = dynamic_imports.get(attr_name) - if module_name is not None: - try: - module = dynamic_import(package, module_name) - return getattr(module, attr_name) - except ImportError as e: - raise ImportError( - f"Failed to import {attr_name} from {module_name}: {e}" - ) from e - except AttributeError as e: - raise AttributeError( - f"Failed to get {attr_name} from {module_name}: {e}" - ) from e - - if sub_packages and attr_name in sub_packages: - return import_module(f".{attr_name}", package) - - raise AttributeError(f"module '{package}' has no attribute '{attr_name}'") - - -def lazy_dir(*, dynamic_imports, sub_packages=None): - """Module-level __dir__ that lists lazily-loadable attributes.""" - lazy_attrs = builtins.list(dynamic_imports.keys()) - if sub_packages: - lazy_attrs.extend(sub_packages) - return builtins.sorted(lazy_attrs) diff --git a/sync-for-payables/src/codat_sync_for_payables/utils/enums.py b/sync-for-payables/src/codat_sync_for_payables/utils/enums.py deleted file mode 100644 index 3324e1bc2..000000000 --- a/sync-for-payables/src/codat_sync_for_payables/utils/enums.py +++ /dev/null @@ -1,134 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -import enum -import sys -from typing import Any - -from pydantic_core import core_schema - - -class OpenEnumMeta(enum.EnumMeta): - # The __call__ method `boundary` kwarg was added in 3.11 and must be present - # for pyright. Refer also: https://github.com/pylint-dev/pylint/issues/9622 - # pylint: disable=unexpected-keyword-arg - # The __call__ method `values` varg must be named for pyright. - # pylint: disable=keyword-arg-before-vararg - - if sys.version_info >= (3, 11): - def __call__( - cls, value, names=None, *values, module=None, qualname=None, type=None, start=1, boundary=None - ): - # The `type` kwarg also happens to be a built-in that pylint flags as - # redeclared. Safe to ignore this lint rule with this scope. - # pylint: disable=redefined-builtin - - if names is not None: - return super().__call__( - value, - names=names, - *values, - module=module, - qualname=qualname, - type=type, - start=start, - boundary=boundary, - ) - - try: - return super().__call__( - value, - names=names, # pyright: ignore[reportArgumentType] - *values, - module=module, - qualname=qualname, - type=type, - start=start, - boundary=boundary, - ) - except ValueError: - return value - else: - def __call__( - cls, value, names=None, *, module=None, qualname=None, type=None, start=1 - ): - # The `type` kwarg also happens to be a built-in that pylint flags as - # redeclared. Safe to ignore this lint rule with this scope. - # pylint: disable=redefined-builtin - - if names is not None: - return super().__call__( - value, - names=names, - module=module, - qualname=qualname, - type=type, - start=start, - ) - - try: - return super().__call__( - value, - names=names, # pyright: ignore[reportArgumentType] - module=module, - qualname=qualname, - type=type, - start=start, - ) - except ValueError: - return value - - def __new__(mcs, name, bases, namespace, **kwargs): - cls = super().__new__(mcs, name, bases, namespace, **kwargs) - - # Add __get_pydantic_core_schema__ to make open enums work correctly - # in union discrimination. In strict mode (used by Pydantic for unions), - # only known enum values match. In lax mode, unknown values are accepted. - def __get_pydantic_core_schema__( - cls_inner: Any, _source_type: Any, _handler: Any - ) -> core_schema.CoreSchema: - # Create a validator that only accepts known enum values (for strict mode) - def validate_strict(v: Any) -> Any: - if isinstance(v, cls_inner): - return v - # Use the parent EnumMeta's __call__ which raises ValueError for unknown values - return enum.EnumMeta.__call__(cls_inner, v) - - # Create a lax validator that accepts unknown values - def validate_lax(v: Any) -> Any: - if isinstance(v, cls_inner): - return v - try: - return enum.EnumMeta.__call__(cls_inner, v) - except ValueError: - # Return the raw value for unknown enum values - return v - - # Determine the base type schema (str or int) - is_int_enum = False - for base in cls_inner.__mro__: - if base is int: - is_int_enum = True - break - if base is str: - break - - base_schema = ( - core_schema.int_schema() - if is_int_enum - else core_schema.str_schema() - ) - - # Use lax_or_strict_schema: - # - strict mode: only known enum values match (raises ValueError for unknown) - # - lax mode: accept any value, return enum member or raw value - return core_schema.lax_or_strict_schema( - lax_schema=core_schema.chain_schema( - [base_schema, core_schema.no_info_plain_validator_function(validate_lax)] - ), - strict_schema=core_schema.chain_schema( - [base_schema, core_schema.no_info_plain_validator_function(validate_strict)] - ), - ) - - setattr(cls, "__get_pydantic_core_schema__", classmethod(__get_pydantic_core_schema__)) - return cls diff --git a/sync-for-payables/src/codat_sync_for_payables/utils/eventstreaming.py b/sync-for-payables/src/codat_sync_for_payables/utils/eventstreaming.py deleted file mode 100644 index 3bdcd6d3d..000000000 --- a/sync-for-payables/src/codat_sync_for_payables/utils/eventstreaming.py +++ /dev/null @@ -1,309 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -import re -import json -from dataclasses import dataclass, asdict -from typing import ( - Any, - Callable, - Generic, - TypeVar, - Optional, - Generator, - AsyncGenerator, - Tuple, -) -import httpx - -T = TypeVar("T") - - -class EventStream(Generic[T]): - # Holds a reference to the SDK client to avoid it being garbage collected - # and cause termination of the underlying httpx client. - client_ref: Optional[object] - response: httpx.Response - generator: Generator[T, None, None] - _closed: bool - - def __init__( - self, - response: httpx.Response, - decoder: Callable[[str], T], - sentinel: Optional[str] = None, - client_ref: Optional[object] = None, - data_required: bool = True, - ): - self.response = response - self.generator = stream_events( - response, decoder, sentinel, data_required=data_required - ) - self.client_ref = client_ref - self._closed = False - - def __iter__(self): - return self - - def __next__(self): - if self._closed: - raise StopIteration - return next(self.generator) - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - self._closed = True - self.response.close() - - -class EventStreamAsync(Generic[T]): - # Holds a reference to the SDK client to avoid it being garbage collected - # and cause termination of the underlying httpx client. - client_ref: Optional[object] - response: httpx.Response - generator: AsyncGenerator[T, None] - _closed: bool - - def __init__( - self, - response: httpx.Response, - decoder: Callable[[str], T], - sentinel: Optional[str] = None, - client_ref: Optional[object] = None, - data_required: bool = True, - ): - self.response = response - self.generator = stream_events_async( - response, decoder, sentinel, data_required=data_required - ) - self.client_ref = client_ref - self._closed = False - - def __aiter__(self): - return self - - async def __anext__(self): - if self._closed: - raise StopAsyncIteration - return await self.generator.__anext__() - - async def __aenter__(self): - return self - - async def __aexit__(self, exc_type, exc_val, exc_tb): - self._closed = True - await self.response.aclose() - - -@dataclass -class ServerEvent: - id: Optional[str] = None - event: Optional[str] = None - data: Any = None - retry: Optional[int] = None - - -MESSAGE_BOUNDARIES = [ - b"\r\n\r\n", - b"\r\n\r", - b"\r\n\n", - b"\r\r\n", - b"\n\r\n", - b"\r\r", - b"\n\r", - b"\n\n", -] - -UTF8_BOM = b"\xef\xbb\xbf" - - -async def stream_events_async( - response: httpx.Response, - decoder: Callable[[str], T], - sentinel: Optional[str] = None, - data_required: bool = True, -) -> AsyncGenerator[T, None]: - buffer = bytearray() - position = 0 - event_id: Optional[str] = None - async for chunk in response.aiter_bytes(): - if len(buffer) == 0 and chunk.startswith(UTF8_BOM): - chunk = chunk[len(UTF8_BOM) :] - buffer += chunk - for i in range(position, len(buffer)): - char = buffer[i : i + 1] - seq: Optional[bytes] = None - if char in [b"\r", b"\n"]: - for boundary in MESSAGE_BOUNDARIES: - seq = _peek_sequence(i, buffer, boundary) - if seq is not None: - break - if seq is None: - continue - - block = buffer[position:i] - position = i + len(seq) - event, discard, event_id = _parse_event( - raw=block, - decoder=decoder, - sentinel=sentinel, - event_id=event_id, - data_required=data_required, - ) - if event is not None: - yield event - if discard: - await response.aclose() - return - - if position > 0: - buffer = buffer[position:] - position = 0 - - event, discard, _ = _parse_event( - raw=buffer, - decoder=decoder, - sentinel=sentinel, - event_id=event_id, - data_required=data_required, - ) - if event is not None: - yield event - - -def stream_events( - response: httpx.Response, - decoder: Callable[[str], T], - sentinel: Optional[str] = None, - data_required: bool = True, -) -> Generator[T, None, None]: - buffer = bytearray() - position = 0 - event_id: Optional[str] = None - for chunk in response.iter_bytes(): - if len(buffer) == 0 and chunk.startswith(UTF8_BOM): - chunk = chunk[len(UTF8_BOM) :] - buffer += chunk - for i in range(position, len(buffer)): - char = buffer[i : i + 1] - seq: Optional[bytes] = None - if char in [b"\r", b"\n"]: - for boundary in MESSAGE_BOUNDARIES: - seq = _peek_sequence(i, buffer, boundary) - if seq is not None: - break - if seq is None: - continue - - block = buffer[position:i] - position = i + len(seq) - event, discard, event_id = _parse_event( - raw=block, - decoder=decoder, - sentinel=sentinel, - event_id=event_id, - data_required=data_required, - ) - if event is not None: - yield event - if discard: - response.close() - return - - if position > 0: - buffer = buffer[position:] - position = 0 - - event, discard, _ = _parse_event( - raw=buffer, - decoder=decoder, - sentinel=sentinel, - event_id=event_id, - data_required=data_required, - ) - if event is not None: - yield event - - -def _parse_event( - *, - raw: bytearray, - decoder: Callable[[str], T], - sentinel: Optional[str] = None, - event_id: Optional[str] = None, - data_required: bool = True, -) -> Tuple[Optional[T], bool, Optional[str]]: - block = raw.decode() - lines = re.split(r"\r?\n|\r", block) - publish = False - event = ServerEvent() - data = "" - for line in lines: - if not line: - continue - - delim = line.find(":") - if delim == 0: - continue - - field = line - value = "" - if delim > 0: - field = line[0:delim] - value = line[delim + 1 :] if delim < len(line) - 1 else "" - if len(value) and value[0] == " ": - value = value[1:] - - if field == "event": - event.event = value - publish = True - elif field == "data": - data += value + "\n" - publish = True - elif field == "id": - publish = True - if "\x00" not in value: - event_id = value - elif field == "retry": - if value.isdigit(): - event.retry = int(value) - publish = True - - event.id = event_id - - if sentinel and data == f"{sentinel}\n": - return None, True, event_id - - # Skip data-less events when data is required - if not data and publish and data_required: - return None, False, event_id - - if data: - data = data[:-1] - try: - event.data = json.loads(data) - except json.JSONDecodeError: - event.data = data - - out = None - if publish: - out_dict = { - k: v - for k, v in asdict(event).items() - if v is not None or (k == "data" and data) - } - out = decoder(json.dumps(out_dict)) - - return out, False, event_id - - -def _peek_sequence(position: int, buffer: bytearray, sequence: bytes): - if len(sequence) > (len(buffer) - position): - return None - - for i, seq in enumerate(sequence): - if buffer[position + i] != seq: - return None - - return sequence diff --git a/sync-for-payables/src/codat_sync_for_payables/utils/forms.py b/sync-for-payables/src/codat_sync_for_payables/utils/forms.py deleted file mode 100644 index f961e76be..000000000 --- a/sync-for-payables/src/codat_sync_for_payables/utils/forms.py +++ /dev/null @@ -1,234 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from typing import ( - Any, - Dict, - get_type_hints, - List, - Tuple, -) -from pydantic import BaseModel -from pydantic.fields import FieldInfo - -from .serializers import marshal_json - -from .metadata import ( - FormMetadata, - MultipartFormMetadata, - find_field_metadata, -) -from .values import _is_set, _val_to_string - - -def _populate_form( - field_name: str, - explode: bool, - obj: Any, - delimiter: str, - form: Dict[str, List[str]], -): - if not _is_set(obj): - return form - - if isinstance(obj, BaseModel): - items = [] - - obj_fields: Dict[str, FieldInfo] = obj.__class__.model_fields - for name in obj_fields: - obj_field = obj_fields[name] - obj_field_name = obj_field.alias if obj_field.alias is not None else name - if obj_field_name == "": - continue - - val = getattr(obj, name) - if not _is_set(val): - continue - - if explode: - form[obj_field_name] = [_val_to_string(val)] - else: - items.append(f"{obj_field_name}{delimiter}{_val_to_string(val)}") - - if len(items) > 0: - form[field_name] = [delimiter.join(items)] - elif isinstance(obj, Dict): - items = [] - for key, value in obj.items(): - if not _is_set(value): - continue - - if explode: - form[key] = [_val_to_string(value)] - else: - items.append(f"{key}{delimiter}{_val_to_string(value)}") - - if len(items) > 0: - form[field_name] = [delimiter.join(items)] - elif isinstance(obj, List): - items = [] - - for value in obj: - if not _is_set(value): - continue - - if explode: - 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: - form[field_name] = [delimiter.join([str(item) for item in items])] - else: - form[field_name] = [_val_to_string(obj)] - - return form - - -def _extract_file_properties(file_obj: Any) -> Tuple[str, Any, Any]: - """Extract file name, content, and content type from a file object.""" - file_fields: Dict[str, FieldInfo] = file_obj.__class__.model_fields - - file_name = "" - content = None - content_type = None - - for file_field_name in file_fields: - file_field = file_fields[file_field_name] - - file_metadata = find_field_metadata(file_field, MultipartFormMetadata) - if file_metadata is None: - continue - - if file_metadata.content: - content = getattr(file_obj, file_field_name, None) - elif file_field_name == "content_type": - content_type = getattr(file_obj, file_field_name, None) - else: - file_name = getattr(file_obj, file_field_name) - - if file_name == "" or content is None: - raise ValueError("invalid multipart/form-data file") - - return file_name, content, content_type - - -def serialize_multipart_form( - media_type: str, request: Any -) -> Tuple[str, Dict[str, Any], List[Tuple[str, Any]]]: - form: Dict[str, Any] = {} - files: List[Tuple[str, Any]] = [] - - if not isinstance(request, BaseModel): - raise TypeError("invalid request body type") - - request_fields: Dict[str, FieldInfo] = request.__class__.model_fields - request_field_types = get_type_hints(request.__class__) - - for name in request_fields: - field = request_fields[name] - - val = getattr(request, name) - if not _is_set(val): - continue - - field_metadata = find_field_metadata(field, MultipartFormMetadata) - if not field_metadata: - continue - - f_name = field.alias if field.alias else name - - if field_metadata.file: - if isinstance(val, List): - # Handle array of files - array_field_name = f_name + "[]" - for file_obj in val: - if not _is_set(file_obj): - continue - - file_name, content, content_type = _extract_file_properties( - file_obj - ) - - if content_type is not None: - files.append( - (array_field_name, (file_name, content, content_type)) - ) - else: - files.append((array_field_name, (file_name, content))) - else: - # Handle single file - file_name, content, content_type = _extract_file_properties(val) - - if content_type is not None: - files.append((f_name, (file_name, content, content_type))) - else: - files.append((f_name, (file_name, content))) - elif field_metadata.json: - files.append( - ( - f_name, - ( - None, - marshal_json(val, request_field_types[name]), - "application/json", - ), - ) - ) - else: - if isinstance(val, List): - values = [] - - for value in val: - if not _is_set(value): - continue - values.append(_val_to_string(value)) - - array_field_name = f_name + "[]" - form[array_field_name] = values - else: - form[f_name] = _val_to_string(val) - return media_type, form, files - - -def serialize_form_data(data: Any) -> Dict[str, Any]: - form: Dict[str, List[str]] = {} - - if isinstance(data, BaseModel): - data_fields: Dict[str, FieldInfo] = data.__class__.model_fields - data_field_types = get_type_hints(data.__class__) - for name in data_fields: - field = data_fields[name] - - val = getattr(data, name) - if not _is_set(val): - continue - - metadata = find_field_metadata(field, FormMetadata) - if metadata is None: - continue - - f_name = field.alias if field.alias is not None else name - - if metadata.json: - form[f_name] = [marshal_json(val, data_field_types[name])] - else: - if metadata.style == "form": - _populate_form( - f_name, - metadata.explode, - val, - ",", - form, - ) - else: - raise ValueError(f"Invalid form style for field {name}") - elif isinstance(data, Dict): - for key, value in data.items(): - if _is_set(value): - form[key] = [_val_to_string(value)] - else: - raise TypeError(f"Invalid request body type {type(data)} for form data") - - return form diff --git a/sync-for-payables/src/codat_sync_for_payables/utils/headers.py b/sync-for-payables/src/codat_sync_for_payables/utils/headers.py deleted file mode 100644 index 37864cbbb..000000000 --- a/sync-for-payables/src/codat_sync_for_payables/utils/headers.py +++ /dev/null @@ -1,136 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from typing import ( - Any, - Dict, - List, - Optional, -) -from httpx import Headers -from pydantic import BaseModel -from pydantic.fields import FieldInfo - -from .metadata import ( - HeaderMetadata, - find_field_metadata, -) - -from .values import _is_set, _populate_from_globals, _val_to_string - - -def get_headers(headers_params: Any, gbls: Optional[Any] = None) -> Dict[str, str]: - headers: Dict[str, str] = {} - - globals_already_populated = [] - if _is_set(headers_params): - globals_already_populated = _populate_headers(headers_params, gbls, headers, []) - if _is_set(gbls): - _populate_headers(gbls, None, headers, globals_already_populated) - - return headers - - -def _populate_headers( - headers_params: Any, - gbls: Any, - header_values: Dict[str, str], - skip_fields: List[str], -) -> List[str]: - globals_already_populated: List[str] = [] - - if not isinstance(headers_params, BaseModel): - return globals_already_populated - - param_fields: Dict[str, FieldInfo] = headers_params.__class__.model_fields - for name in param_fields: - if name in skip_fields: - continue - - field = param_fields[name] - f_name = field.alias if field.alias is not None else name - - metadata = find_field_metadata(field, HeaderMetadata) - if metadata is None: - continue - - value, global_found = _populate_from_globals( - name, getattr(headers_params, name), HeaderMetadata, gbls - ) - if global_found: - globals_already_populated.append(name) - value = _serialize_header(metadata.explode, value) - - if value != "": - header_values[f_name] = value - - return globals_already_populated - - -def _serialize_header(explode: bool, obj: Any) -> str: - if not _is_set(obj): - return "" - - if isinstance(obj, BaseModel): - items = [] - obj_fields: Dict[str, FieldInfo] = obj.__class__.model_fields - for name in obj_fields: - obj_field = obj_fields[name] - obj_param_metadata = find_field_metadata(obj_field, HeaderMetadata) - - if not obj_param_metadata: - continue - - f_name = obj_field.alias if obj_field.alias is not None else name - - val = getattr(obj, name) - if not _is_set(val): - continue - - if explode: - items.append(f"{f_name}={_val_to_string(val)}") - else: - items.append(f_name) - items.append(_val_to_string(val)) - - if len(items) > 0: - return ",".join(items) - elif isinstance(obj, Dict): - items = [] - - for key, value in obj.items(): - if not _is_set(value): - continue - - if explode: - 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): - items = [] - - for value in obj: - if not _is_set(value): - continue - - items.append(_val_to_string(value)) - - if len(items) > 0: - return ",".join(items) - elif _is_set(obj): - return f"{_val_to_string(obj)}" - - return "" - - -def get_response_headers(headers: Headers) -> Dict[str, List[str]]: - res: Dict[str, List[str]] = {} - for k, v in headers.items(): - if not k in res: - res[k] = [] - - res[k].append(v) - return res diff --git a/sync-for-payables/src/codat_sync_for_payables/utils/logger.py b/sync-for-payables/src/codat_sync_for_payables/utils/logger.py deleted file mode 100644 index b661aff65..000000000 --- a/sync-for-payables/src/codat_sync_for_payables/utils/logger.py +++ /dev/null @@ -1,22 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -import httpx -from typing import Any, Protocol - - -class Logger(Protocol): - def debug(self, msg: str, *args: Any, **kwargs: Any) -> None: - pass - - -class NoOpLogger: - def debug(self, msg: str, *args: Any, **kwargs: Any) -> None: - pass - - -def get_body_content(req: httpx.Request) -> str: - return "" if not hasattr(req, "_content") else str(req.content) - - -def get_default_logger() -> Logger: - return NoOpLogger() diff --git a/sync-for-payables/src/codat_sync_for_payables/utils/metadata.py b/sync-for-payables/src/codat_sync_for_payables/utils/metadata.py deleted file mode 100644 index 5abddd588..000000000 --- a/sync-for-payables/src/codat_sync_for_payables/utils/metadata.py +++ /dev/null @@ -1,119 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from typing import Optional, Type, TypeVar, Union -from dataclasses import dataclass -from pydantic.fields import FieldInfo - - -T = TypeVar("T") - - -@dataclass -class SecurityMetadata: - option: bool = False - scheme: bool = False - scheme_type: Optional[str] = None - sub_type: Optional[str] = None - field_name: Optional[str] = None - composite: bool = False - - def get_field_name(self, default: str) -> str: - return self.field_name or default - - -@dataclass -class ParamMetadata: - serialization: Optional[str] = None - style: str = "simple" - explode: bool = False - - -@dataclass -class PathParamMetadata(ParamMetadata): - pass - - -@dataclass -class QueryParamMetadata(ParamMetadata): - style: str = "form" - explode: bool = True - - -@dataclass -class HeaderMetadata(ParamMetadata): - pass - - -@dataclass -class RequestMetadata: - media_type: str = "application/octet-stream" - - -@dataclass -class MultipartFormMetadata: - file: bool = False - content: bool = False - json: bool = False - - -@dataclass -class FormMetadata: - json: bool = False - style: str = "form" - explode: bool = True - - -class FieldMetadata: - security: Optional[SecurityMetadata] = None - path: Optional[PathParamMetadata] = None - query: Optional[QueryParamMetadata] = None - header: Optional[HeaderMetadata] = None - request: Optional[RequestMetadata] = None - form: Optional[FormMetadata] = None - multipart: Optional[MultipartFormMetadata] = None - - def __init__( - self, - security: Optional[SecurityMetadata] = None, - path: Optional[Union[PathParamMetadata, bool]] = None, - query: Optional[Union[QueryParamMetadata, bool]] = None, - header: Optional[Union[HeaderMetadata, bool]] = None, - request: Optional[Union[RequestMetadata, bool]] = None, - form: Optional[Union[FormMetadata, bool]] = None, - multipart: Optional[Union[MultipartFormMetadata, bool]] = None, - ): - self.security = security - self.path = PathParamMetadata() if isinstance(path, bool) else path - self.query = QueryParamMetadata() if isinstance(query, bool) else query - self.header = HeaderMetadata() if isinstance(header, bool) else header - self.request = RequestMetadata() if isinstance(request, bool) else request - self.form = FormMetadata() if isinstance(form, bool) else form - self.multipart = ( - MultipartFormMetadata() if isinstance(multipart, bool) else multipart - ) - - -def find_field_metadata(field_info: FieldInfo, metadata_type: Type[T]) -> Optional[T]: - metadata = find_metadata(field_info, FieldMetadata) - if not metadata: - return None - - fields = metadata.__dict__ - - for field in fields: - if isinstance(fields[field], metadata_type): - return fields[field] - - return None - - -def find_metadata(field_info: FieldInfo, metadata_type: Type[T]) -> Optional[T]: - metadata = field_info.metadata - if not metadata: - return None - - for md in metadata: - if isinstance(md, metadata_type): - return md - - return None diff --git a/sync-for-payables/src/codat_sync_for_payables/utils/queryparams.py b/sync-for-payables/src/codat_sync_for_payables/utils/queryparams.py deleted file mode 100644 index c04e0db82..000000000 --- a/sync-for-payables/src/codat_sync_for_payables/utils/queryparams.py +++ /dev/null @@ -1,217 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from typing import ( - Any, - Dict, - get_type_hints, - List, - Optional, -) - -from pydantic import BaseModel -from pydantic.fields import FieldInfo - -from .metadata import ( - QueryParamMetadata, - find_field_metadata, -) -from .values import ( - _get_serialized_params, - _is_set, - _populate_from_globals, - _val_to_string, -) -from .forms import _populate_form - - -def get_query_params( - query_params: Any, - gbls: Optional[Any] = None, - allow_empty_value: Optional[List[str]] = None, -) -> Dict[str, List[str]]: - params: Dict[str, List[str]] = {} - - globals_already_populated = _populate_query_params(query_params, gbls, params, [], allow_empty_value) - if _is_set(gbls): - _populate_query_params(gbls, None, params, globals_already_populated, allow_empty_value) - - return params - - -def _populate_query_params( - query_params: Any, - gbls: Any, - query_param_values: Dict[str, List[str]], - skip_fields: List[str], - allow_empty_value: Optional[List[str]] = None, -) -> List[str]: - globals_already_populated: List[str] = [] - - if not isinstance(query_params, BaseModel): - return globals_already_populated - - param_fields: Dict[str, FieldInfo] = query_params.__class__.model_fields - param_field_types = get_type_hints(query_params.__class__) - for name in param_fields: - if name in skip_fields: - continue - - field = param_fields[name] - - metadata = find_field_metadata(field, QueryParamMetadata) - if not metadata: - continue - - value = getattr(query_params, name) if _is_set(query_params) else None - - value, global_found = _populate_from_globals( - name, value, QueryParamMetadata, gbls - ) - if global_found: - globals_already_populated.append(name) - - f_name = field.alias if field.alias is not None else name - - allow_empty_set = set(allow_empty_value or []) - should_include_empty = f_name in allow_empty_set and ( - value is None or value == [] or value == "" - ) - - if should_include_empty: - query_param_values[f_name] = [""] - continue - - serialization = metadata.serialization - if serialization is not None: - serialized_parms = _get_serialized_params( - metadata, f_name, value, param_field_types[name] - ) - 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.style - if style == "deepObject": - _populate_deep_object_query_params(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 NotImplementedError( - f"query param style {style} not yet supported" - ) - - return globals_already_populated - - -def _populate_deep_object_query_params( - field_name: str, - obj: Any, - params: Dict[str, List[str]], -): - if not _is_set(obj): - return - - if isinstance(obj, BaseModel): - _populate_deep_object_query_params_basemodel(field_name, obj, params) - elif isinstance(obj, Dict): - _populate_deep_object_query_params_dict(field_name, obj, params) - - -def _populate_deep_object_query_params_basemodel( - prior_params_key: str, - obj: Any, - params: Dict[str, List[str]], -): - if not _is_set(obj) or not isinstance(obj, BaseModel): - return - - obj_fields: Dict[str, FieldInfo] = obj.__class__.model_fields - for name in obj_fields: - obj_field = obj_fields[name] - - f_name = obj_field.alias if obj_field.alias is not None else name - - params_key = f"{prior_params_key}[{f_name}]" - - obj_param_metadata = find_field_metadata(obj_field, QueryParamMetadata) - if not _is_set(obj_param_metadata): - continue - - obj_val = getattr(obj, name) - if not _is_set(obj_val): - continue - - if isinstance(obj_val, BaseModel): - _populate_deep_object_query_params_basemodel(params_key, obj_val, params) - elif isinstance(obj_val, Dict): - _populate_deep_object_query_params_dict(params_key, obj_val, params) - elif isinstance(obj_val, List): - _populate_deep_object_query_params_list(params_key, obj_val, params) - else: - params[params_key] = [_val_to_string(obj_val)] - - -def _populate_deep_object_query_params_dict( - prior_params_key: str, - value: Dict, - params: Dict[str, List[str]], -): - if not _is_set(value): - return - - for key, val in value.items(): - if not _is_set(val): - continue - - params_key = f"{prior_params_key}[{key}]" - - if isinstance(val, BaseModel): - _populate_deep_object_query_params_basemodel(params_key, val, params) - elif isinstance(val, Dict): - _populate_deep_object_query_params_dict(params_key, val, params) - elif isinstance(val, List): - _populate_deep_object_query_params_list(params_key, val, params) - else: - params[params_key] = [_val_to_string(val)] - - -def _populate_deep_object_query_params_list( - params_key: str, - value: List, - params: Dict[str, List[str]], -): - if not _is_set(value): - return - - for val in value: - if not _is_set(val): - continue - - if params.get(params_key) is None: - params[params_key] = [] - - params[params_key].append(_val_to_string(val)) - - -def _populate_delimited_query_params( - metadata: QueryParamMetadata, - field_name: str, - obj: Any, - delimiter: str, - query_param_values: Dict[str, List[str]], -): - _populate_form( - field_name, - metadata.explode, - obj, - delimiter, - query_param_values, - ) diff --git a/sync-for-payables/src/codat_sync_for_payables/utils/requestbodies.py b/sync-for-payables/src/codat_sync_for_payables/utils/requestbodies.py deleted file mode 100644 index 591415af8..000000000 --- a/sync-for-payables/src/codat_sync_for_payables/utils/requestbodies.py +++ /dev/null @@ -1,67 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -import io -from dataclasses import dataclass -import re -from typing import ( - Any, - Optional, -) - -from .forms import serialize_form_data, serialize_multipart_form - -from .serializers import marshal_json - -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", -} - - -@dataclass -class SerializedRequestBody: - media_type: Optional[str] = None - content: Optional[Any] = None - data: Optional[Any] = None - files: Optional[Any] = None - - -def serialize_request_body( - request_body: Any, - nullable: bool, - optional: bool, - serialization_method: str, - request_body_type, -) -> Optional[SerializedRequestBody]: - if request_body is None: - if not nullable and optional: - return None - - media_type = SERIALIZATION_METHOD_TO_CONTENT_TYPE[serialization_method] - - serialized_request_body = SerializedRequestBody(media_type) - - if re.match(r"^(application|text)\/([^+]+\+)*json.*", media_type) is not None: - serialized_request_body.content = marshal_json(request_body, request_body_type) - - elif re.match(r"^multipart\/.*", media_type) is not None: - ( - serialized_request_body.media_type, - serialized_request_body.data, - serialized_request_body.files, - ) = serialize_multipart_form(media_type, request_body) - elif re.match(r"^application\/x-www-form-urlencoded.*", media_type) is not None: - serialized_request_body.data = serialize_form_data(request_body) - elif isinstance(request_body, (bytes, bytearray, io.BytesIO, io.BufferedReader)): - serialized_request_body.content = request_body - elif isinstance(request_body, str): - serialized_request_body.content = request_body - else: - raise TypeError( - f"invalid request body type {type(request_body)} for mediaType {media_type}" - ) - - return serialized_request_body diff --git a/sync-for-payables/src/codat_sync_for_payables/utils/retries.py b/sync-for-payables/src/codat_sync_for_payables/utils/retries.py index af07d4e94..28b22e85e 100644 --- a/sync-for-payables/src/codat_sync_for_payables/utils/retries.py +++ b/sync-for-payables/src/codat_sync_for_payables/utils/retries.py @@ -1,13 +1,13 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""Retry configuration matching Speakeasy SDK surface, with runtime backoff loop.""" + +from __future__ import annotations -import asyncio import random import time +import urllib3 from datetime import datetime from email.utils import parsedate_to_datetime -from typing import List, Optional - -import httpx +from typing import Any, Callable, Iterable, List, Optional, Set class BackoffStrategy: @@ -18,10 +18,10 @@ class BackoffStrategy: def __init__( self, - initial_interval: int, - max_interval: int, - exponent: float, - max_elapsed_time: int, + initial_interval: int = 500, + max_interval: int = 60000, + exponent: float = 1.5, + max_elapsed_time: int = 3600000, ): self.initial_interval = initial_interval self.max_interval = max_interval @@ -35,10 +35,13 @@ class RetryConfig: retry_connection_errors: bool def __init__( - self, strategy: str, backoff: BackoffStrategy, retry_connection_errors: bool + self, + strategy: str = "backoff", + backoff: Optional[BackoffStrategy] = None, + retry_connection_errors: bool = True, ): self.strategy = strategy - self.backoff = backoff + self.backoff = backoff if backoff is not None else BackoffStrategy() self.retry_connection_errors = retry_connection_errors @@ -51,221 +54,119 @@ def __init__(self, config: RetryConfig, status_codes: List[str]): self.status_codes = status_codes -class TemporaryError(Exception): - response: httpx.Response - retry_after: Optional[int] - - def __init__(self, response: httpx.Response): - self.response = response - self.retry_after = _parse_retry_after_header(response) - - -class PermanentError(Exception): - inner: Exception - - def __init__(self, inner: Exception): - self.inner = inner - - -def _parse_retry_after_header(response: httpx.Response) -> Optional[int]: - """Parse Retry-After header from response. - - Returns: - Retry interval in milliseconds, or None if header is missing or invalid. - """ - retry_after_header = response.headers.get("retry-after") - if not retry_after_header: +# Default retryable status codes from the OAS (x-speakeasy-retries.statusCodes). +# Entries may be ints or strings like "5XX" denoting wildcards across a hundred-block. +DEFAULT_RETRY_STATUS_CODES: List[Any] = [408, 429, '5XX'] + + +def _matches_status(code: int, retry_codes: Iterable[Any]) -> bool: + for entry in retry_codes: + if isinstance(entry, int) and entry == code: + return True + if isinstance(entry, str): + entry_u = entry.upper() + if entry_u.endswith("XX") and len(entry_u) == 3 and entry_u[0].isdigit(): + if (code // 100) == int(entry_u[0]): + return True + else: + try: + if int(entry_u) == code: + return True + except ValueError: + pass + return False + + +def _retry_after_ms(exc: Any) -> Optional[int]: + """Milliseconds to wait from a response's Retry-After header, or None if absent. + Accepts an integer number of seconds or an HTTP date, matching Speakeasy and the + TypeScript runtime. A past date clamps to 0.""" + headers = getattr(exc, "headers", None) + if not headers: return None - - try: - seconds = float(retry_after_header) - return round(seconds * 1000) - except ValueError: - pass - + getter = getattr(headers, "get", None) + if getter is None: + return None + value = getter("Retry-After") + if value is None: + value = getter("retry-after") + if value is None: + return None + text = str(value).strip() + if text.isdigit(): + return int(text) * 1000 try: - retry_date = parsedate_to_datetime(retry_after_header) - delta = (retry_date - datetime.now(retry_date.tzinfo)).total_seconds() - return round(max(0, delta) * 1000) - except (ValueError, TypeError): - pass - - return None - - -def _get_sleep_interval( - exception: Exception, - initial_interval: int, - max_interval: int, - exponent: float, - retries: int, -) -> float: - """Get sleep interval for retry with exponential backoff. - - Args: - exception: The exception that triggered the retry. - initial_interval: Initial retry interval in milliseconds. - max_interval: Maximum retry interval in milliseconds. - exponent: Base for exponential backoff calculation. - retries: Current retry attempt count. - - Returns: - Sleep interval in seconds. + parsed = parsedate_to_datetime(text) + except (TypeError, ValueError): + return None + if parsed is None: + return None + now = datetime.now(parsed.tzinfo) if parsed.tzinfo is not None else datetime.utcnow() + delta_ms = int((parsed - now).total_seconds() * 1000) + return delta_ms if delta_ms > 0 else 0 + + +def execute_with_retries( + call_fn: Callable[[], Any], + retry_config: Optional[RetryConfig], + retry_status_codes: Optional[Iterable[Any]] = None, +) -> Any: + """Run call_fn() and retry on retryable failures per retry_config. + + `retry_config=None` means nothing was supplied, so fall back to the default backoff + policy (retry by default, matching Speakeasy). A RetryConfig with strategy "none" + disables retries -> just one attempt. `retry_status_codes` falls back to + DEFAULT_RETRY_STATUS_CODES. """ - if ( - isinstance(exception, TemporaryError) - and exception.retry_after is not None - and exception.retry_after > 0 - ): - return exception.retry_after / 1000 - - sleep = (initial_interval / 1000) * exponent**retries + random.uniform(0, 1) - return min(sleep, max_interval / 1000) - - -def retry(func, retries: Retries): - if retries.config.strategy == "backoff": - - def do_request() -> httpx.Response: - res: httpx.Response - try: - res = func() - - for code in retries.status_codes: - if "X" in code.upper(): - code_range = int(code[0]) - - status_major = res.status_code / 100 - - if code_range <= status_major < code_range + 1: - raise TemporaryError(res) - else: - parsed_code = int(code) - - if res.status_code == parsed_code: - raise TemporaryError(res) - except (httpx.NetworkError, httpx.TimeoutException) as exception: - if retries.config.retry_connection_errors: - raise - - raise PermanentError(exception) from exception - except TemporaryError: - raise - except Exception as exception: - raise PermanentError(exception) from exception - - return res - - return retry_with_backoff( - do_request, - retries.config.backoff.initial_interval, - retries.config.backoff.max_interval, - retries.config.backoff.exponent, - retries.config.backoff.max_elapsed_time, - ) - - return func() - - -async def retry_async(func, retries: Retries): - if retries.config.strategy == "backoff": - - async def do_request() -> httpx.Response: - res: httpx.Response - try: - res = await func() - - for code in retries.status_codes: - if "X" in code.upper(): - code_range = int(code[0]) - - status_major = res.status_code / 100 - - if code_range <= status_major < code_range + 1: - raise TemporaryError(res) - else: - parsed_code = int(code) - - if res.status_code == parsed_code: - raise TemporaryError(res) - except (httpx.NetworkError, httpx.TimeoutException) as exception: - if retries.config.retry_connection_errors: - raise - - raise PermanentError(exception) from exception - except TemporaryError: - raise - except Exception as exception: - raise PermanentError(exception) from exception - - return res - - return await retry_with_backoff_async( - do_request, - retries.config.backoff.initial_interval, - retries.config.backoff.max_interval, - retries.config.backoff.exponent, - retries.config.backoff.max_elapsed_time, - ) - - return await func() - - -def retry_with_backoff( - func, - initial_interval=500, - max_interval=60000, - exponent=1.5, - max_elapsed_time=3600000, -): - start = round(time.time() * 1000) - retries = 0 - + if retry_config is None: + retry_config = RetryConfig() + if getattr(retry_config, "strategy", "backoff") == "none": + return call_fn() + + codes = retry_status_codes if retry_status_codes is not None else DEFAULT_RETRY_STATUS_CODES + backoff = retry_config.backoff + elapsed_ms = 0 + attempt = 0 + last_exc: Optional[BaseException] = None while True: try: - return func() - except PermanentError as exception: - raise exception.inner - except Exception as exception: # pylint: disable=broad-exception-caught - now = round(time.time() * 1000) - if now - start > max_elapsed_time: - if isinstance(exception, TemporaryError): - return exception.response - - raise - - sleep = _get_sleep_interval( - exception, initial_interval, max_interval, exponent, retries + return call_fn() + except Exception as exc: + status = getattr(exc, "status", None) + if status is None: + status = getattr(exc, "status_code", None) + is_retryable_status = isinstance(status, int) and _matches_status(status, codes) + is_conn_err = retry_config.retry_connection_errors and ( + status == 0 or isinstance(exc, urllib3.exceptions.HTTPError) ) - time.sleep(sleep) - retries += 1 - - -async def retry_with_backoff_async( - func, - initial_interval=500, - max_interval=60000, - exponent=1.5, - max_elapsed_time=3600000, -): - start = round(time.time() * 1000) - retries = 0 - - while True: - try: - return await func() - except PermanentError as exception: - raise exception.inner - except Exception as exception: # pylint: disable=broad-exception-caught - now = round(time.time() * 1000) - if now - start > max_elapsed_time: - if isinstance(exception, TemporaryError): - return exception.response - + if not (is_retryable_status or is_conn_err): raise - - sleep = _get_sleep_interval( - exception, initial_interval, max_interval, exponent, retries + last_exc = exc + + # Decide sleep duration; abort if total elapsed exceeds budget + retry_after_ms = _retry_after_ms(last_exc) + if retry_after_ms is not None: + sleep_ms = min(retry_after_ms, backoff.max_interval) + else: + interval = min( + backoff.initial_interval * (backoff.exponent ** attempt), + backoff.max_interval, ) - await asyncio.sleep(sleep) - retries += 1 + # half-jitter + sleep_ms = int(interval / 2 + random.random() * (interval / 2)) + if elapsed_ms + sleep_ms > backoff.max_elapsed_time: + if last_exc is not None: + raise last_exc + return None + time.sleep(sleep_ms / 1000.0) + elapsed_ms += sleep_ms + attempt += 1 + + +__all__ = [ + "BackoffStrategy", + "RetryConfig", + "Retries", + "DEFAULT_RETRY_STATUS_CODES", + "execute_with_retries", +] diff --git a/sync-for-payables/src/codat_sync_for_payables/utils/security.py b/sync-for-payables/src/codat_sync_for_payables/utils/security.py deleted file mode 100644 index 42d8d78e9..000000000 --- a/sync-for-payables/src/codat_sync_for_payables/utils/security.py +++ /dev/null @@ -1,198 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -import base64 -from typing import ( - Any, - Dict, - List, - Optional, - Tuple, -) -from pydantic import BaseModel -from pydantic.fields import FieldInfo - -from .metadata import ( - SecurityMetadata, - find_field_metadata, -) - - -def get_security( - security: Any, allowed_fields: Optional[List[str]] = None -) -> Tuple[Dict[str, str], Dict[str, List[str]]]: - headers: Dict[str, str] = {} - query_params: Dict[str, List[str]] = {} - - if security is None: - return headers, query_params - - if not isinstance(security, BaseModel): - raise TypeError("security must be a pydantic model") - - sec_fields: Dict[str, FieldInfo] = security.__class__.model_fields - sec_field_names = ( - list(sec_fields.keys()) if allowed_fields is None else allowed_fields - ) - - for name in sec_field_names: - if name not in sec_fields: - continue - - sec_field = sec_fields[name] - - value = getattr(security, name) - if value is None: - continue - - metadata = find_field_metadata(sec_field, SecurityMetadata) - if metadata is None: - continue - if metadata.option: - _parse_security_option(headers, query_params, value) - return headers, query_params - if metadata.scheme: - # Special case for basic auth or custom auth which could be a flattened model - if metadata.sub_type in ["basic", "custom"] and not isinstance( - value, BaseModel - ): - _parse_security_scheme(headers, query_params, metadata, name, security) - else: - _parse_security_scheme(headers, query_params, metadata, name, value) - - if not metadata.composite: - return headers, query_params - - return headers, query_params - - -def _parse_security_option( - headers: Dict[str, str], query_params: Dict[str, List[str]], option: Any -): - if not isinstance(option, BaseModel): - raise TypeError("security option must be a pydantic model") - - opt_fields: Dict[str, FieldInfo] = option.__class__.model_fields - - for name in opt_fields: - opt_field = opt_fields[name] - - metadata = find_field_metadata(opt_field, SecurityMetadata) - if metadata is None or not metadata.scheme: - continue - - value = getattr(option, name) - if ( - metadata.scheme_type == "http" - and metadata.sub_type == "basic" - and not isinstance(value, BaseModel) - ): - _parse_basic_auth_scheme(headers, option) - return - - _parse_security_scheme(headers, query_params, metadata, name, value) - - -def _parse_security_scheme( - headers: Dict[str, str], - query_params: Dict[str, List[str]], - scheme_metadata: SecurityMetadata, - field_name: str, - scheme: Any, -): - scheme_type = scheme_metadata.scheme_type - sub_type = scheme_metadata.sub_type - - if isinstance(scheme, BaseModel): - if scheme_type == "http": - if sub_type == "basic": - _parse_basic_auth_scheme(headers, scheme) - return - if sub_type == "custom": - return - - scheme_fields: Dict[str, FieldInfo] = scheme.__class__.model_fields - for name in scheme_fields: - scheme_field = scheme_fields[name] - - metadata = find_field_metadata(scheme_field, SecurityMetadata) - if metadata is None or metadata.field_name is None: - continue - - value = getattr(scheme, name) - - _parse_security_scheme_value( - headers, query_params, scheme_metadata, metadata, name, value - ) - else: - _parse_security_scheme_value( - headers, query_params, scheme_metadata, scheme_metadata, field_name, scheme - ) - - -def _parse_security_scheme_value( - headers: Dict[str, str], - query_params: Dict[str, List[str]], - scheme_metadata: SecurityMetadata, - security_metadata: SecurityMetadata, - field_name: str, - value: Any, -): - scheme_type = scheme_metadata.scheme_type - sub_type = scheme_metadata.sub_type - - header_name = security_metadata.get_field_name(field_name) - - if scheme_type == "apiKey": - if sub_type == "header": - headers[header_name] = value - elif sub_type == "query": - query_params[header_name] = [value] - else: - raise ValueError("sub type {sub_type} not supported") - elif scheme_type == "openIdConnect": - 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) - elif sub_type == "basic": - headers[header_name] = value - elif sub_type == "custom": - return - else: - raise ValueError("sub type {sub_type} not supported") - else: - raise ValueError("scheme type {scheme_type} not supported") - - -def _apply_bearer(token: str) -> str: - return token.lower().startswith("bearer ") and token or f"Bearer {token}" - - -def _parse_basic_auth_scheme(headers: Dict[str, str], scheme: Any): - username = "" - password = "" - - if not isinstance(scheme, BaseModel): - raise TypeError("basic auth scheme must be a pydantic model") - - scheme_fields: Dict[str, FieldInfo] = scheme.__class__.model_fields - for name in scheme_fields: - scheme_field = scheme_fields[name] - - metadata = find_field_metadata(scheme_field, SecurityMetadata) - if metadata is None or metadata.field_name is None: - continue - - field_name = metadata.field_name - value = getattr(scheme, name) - - if field_name == "username": - username = value - if field_name == "password": - password = value - - data = f"{username}:{password}".encode() - headers["Authorization"] = f"Basic {base64.b64encode(data).decode()}" diff --git a/sync-for-payables/src/codat_sync_for_payables/utils/serializers.py b/sync-for-payables/src/codat_sync_for_payables/utils/serializers.py index d2149f8b9..187a4c96a 100644 --- a/sync-for-payables/src/codat_sync_for_payables/utils/serializers.py +++ b/sync-for-payables/src/codat_sync_for_payables/utils/serializers.py @@ -1,18 +1,7 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - +"""Decimal validators and serializers matching Speakeasy's money-field handling.""" +from __future__ import annotations from decimal import Decimal -import functools -import json -import typing -from typing import Any, Dict, List, Tuple, Union, get_args -import typing_extensions -from typing_extensions import get_origin - -import httpx -from pydantic import ConfigDict, create_model -from pydantic_core import from_json - -from ..types.basemodel import BaseModel, Nullable, OptionalNullable, Unset +from codat_sync_for_payables.types import Unset def serialize_decimal(as_str: bool): @@ -21,205 +10,17 @@ def serialize(d): return None if isinstance(d, Unset): return d - if not isinstance(d, Decimal): raise ValueError("Expected Decimal object") - return str(d) if as_str else float(d) - return serialize def validate_decimal(d): if d is None: return None - if isinstance(d, (Decimal, Unset)): return d - if not isinstance(d, (str, int, float)): raise ValueError("Expected string, int or float") - return Decimal(str(d)) - - -def serialize_float(as_str: bool): - def serialize(f): - if f is None: - return None - if isinstance(f, Unset): - return f - - if not isinstance(f, float): - raise ValueError("Expected float") - - return str(f) if as_str else f - - return serialize - - -def validate_float(f): - if f is None: - return None - - if isinstance(f, (float, Unset)): - return f - - if not isinstance(f, str): - raise ValueError("Expected string") - - return float(f) - - -def serialize_int(as_str: bool): - def serialize(i): - if i is None: - return None - if isinstance(i, Unset): - return i - - if not isinstance(i, int): - raise ValueError("Expected int") - - return str(i) if as_str else i - - return serialize - - -def validate_int(b): - if b is None: - return None - - if isinstance(b, (int, Unset)): - return b - - if not isinstance(b, str): - raise ValueError("Expected string") - - return int(b) - - -def validate_const(v): - def validate(c): - if c is None: - return None - - if v != c: - raise ValueError(f"Expected {v}") - - return c - - return validate - - -def unmarshal_json(raw, typ: Any) -> Any: - return unmarshal(from_json(raw), typ) - - -def unmarshal(val, typ: Any) -> Any: - unmarshaller = create_model( - "Unmarshaller", - body=(typ, ...), - __config__=ConfigDict(populate_by_name=True, arbitrary_types_allowed=True), - ) - - m = unmarshaller(body=val) - - # pyright: ignore[reportAttributeAccessIssue] - return m.body # type: ignore - - -def marshal_json(val, typ): - if is_nullable(typ) and val is None: - return "null" - - marshaller = create_model( - "Marshaller", - body=(typ, ...), - __config__=ConfigDict(populate_by_name=True, arbitrary_types_allowed=True), - ) - - m = marshaller(body=val) - - d = m.model_dump(by_alias=True, mode="json", exclude_none=True) - - if len(d) == 0: - return "" - - return json.dumps(d[next(iter(d))], separators=(",", ":")) - - -def is_nullable(field): - origin = get_origin(field) - if origin is Nullable or origin is OptionalNullable: - return True - - if not origin is Union or type(None) not in get_args(field): - return False - - for arg in get_args(field): - if get_origin(arg) is Nullable or get_origin(arg) is OptionalNullable: - return True - - return False - - -def is_union(obj: object) -> bool: - """ - Returns True if the given object is a typing.Union or typing_extensions.Union. - """ - return any( - obj is typing_obj for typing_obj in _get_typing_objects_by_name_of("Union") - ) - - -def stream_to_text(stream: httpx.Response) -> str: - return "".join(stream.iter_text()) - - -async def stream_to_text_async(stream: httpx.Response) -> str: - return "".join([chunk async for chunk in stream.aiter_text()]) - - -def stream_to_bytes(stream: httpx.Response) -> bytes: - return stream.content - - -async def stream_to_bytes_async(stream: httpx.Response) -> bytes: - return await stream.aread() - - -def get_pydantic_model(data: Any, typ: Any) -> Any: - if not _contains_pydantic_model(data): - return unmarshal(data, typ) - - return data - - -def _contains_pydantic_model(data: Any) -> bool: - if isinstance(data, BaseModel): - return True - if isinstance(data, List): - return any(_contains_pydantic_model(item) for item in data) - if isinstance(data, Dict): - return any(_contains_pydantic_model(value) for value in data.values()) - - return False - - -@functools.cache -def _get_typing_objects_by_name_of(name: str) -> Tuple[Any, ...]: - """ - Get typing objects by name from typing and typing_extensions. - Reference: https://typing-extensions.readthedocs.io/en/latest/#runtime-use-of-types - """ - result = tuple( - getattr(module, name) - for module in (typing, typing_extensions) - if hasattr(module, name) - ) - if not result: - raise ValueError( - f"Neither typing nor typing_extensions has an object called {name!r}" - ) - return result diff --git a/sync-for-payables/src/codat_sync_for_payables/utils/unmarshal_json_response.py b/sync-for-payables/src/codat_sync_for_payables/utils/unmarshal_json_response.py deleted file mode 100644 index 0394c9ff4..000000000 --- a/sync-for-payables/src/codat_sync_for_payables/utils/unmarshal_json_response.py +++ /dev/null @@ -1,38 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from typing import Any, Optional, Type, TypeVar, overload - -import httpx - -from .serializers import unmarshal_json -from codat_sync_for_payables.models import errors - -T = TypeVar("T") - - -@overload -def unmarshal_json_response( - typ: Type[T], http_res: httpx.Response, body: Optional[str] = None -) -> T: ... - - -@overload -def unmarshal_json_response( - typ: Any, http_res: httpx.Response, body: Optional[str] = None -) -> Any: ... - - -def unmarshal_json_response( - typ: Any, http_res: httpx.Response, body: Optional[str] = None -) -> Any: - if body is None: - body = http_res.text - try: - return unmarshal_json(body, typ) - except Exception as e: - raise errors.ResponseValidationError( - "Response validation failed", - http_res, - e, - body, - ) from e diff --git a/sync-for-payables/src/codat_sync_for_payables/utils/url.py b/sync-for-payables/src/codat_sync_for_payables/utils/url.py deleted file mode 100644 index c78ccbae4..000000000 --- a/sync-for-payables/src/codat_sync_for_payables/utils/url.py +++ /dev/null @@ -1,155 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from decimal import Decimal -from typing import ( - Any, - Dict, - get_type_hints, - List, - Optional, - Union, - get_args, - get_origin, -) -from pydantic import BaseModel -from pydantic.fields import FieldInfo - -from .metadata import ( - PathParamMetadata, - find_field_metadata, -) -from .values import ( - _get_serialized_params, - _is_set, - _populate_from_globals, - _val_to_string, -) - - -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 _is_set(gbls): - _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] = [] - - if not isinstance(path_params, BaseModel): - return globals_already_populated - - path_param_fields: Dict[str, FieldInfo] = path_params.__class__.model_fields - path_param_field_types = get_type_hints(path_params.__class__) - for name in path_param_fields: - if name in skip_fields: - continue - - field = path_param_fields[name] - - param_metadata = find_field_metadata(field, PathParamMetadata) - if param_metadata is None: - continue - - param = getattr(path_params, name) if _is_set(path_params) else None - param, global_found = _populate_from_globals( - name, param, PathParamMetadata, gbls - ) - if global_found: - globals_already_populated.append(name) - - if not _is_set(param): - continue - - f_name = field.alias if field.alias is not None else name - serialization = param_metadata.serialization - if serialization is not None: - serialized_params = _get_serialized_params( - param_metadata, f_name, param, path_param_field_types[name] - ) - for key, value in serialized_params.items(): - path_param_values[key] = value - else: - pp_vals: List[str] = [] - if param_metadata.style == "simple": - if isinstance(param, List): - for pp_val in param: - if not _is_set(pp_val): - continue - pp_vals.append(_val_to_string(pp_val)) - path_param_values[f_name] = ",".join(pp_vals) - elif isinstance(param, Dict): - for pp_key in param: - if not _is_set(param[pp_key]): - continue - if param_metadata.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[f_name] = ",".join(pp_vals) - elif not isinstance(param, (str, int, float, complex, bool, Decimal)): - param_fields: Dict[str, FieldInfo] = param.__class__.model_fields - for name in param_fields: - param_field = param_fields[name] - - param_value_metadata = find_field_metadata( - param_field, PathParamMetadata - ) - if param_value_metadata is None: - continue - - param_name = ( - param_field.alias if param_field.alias is not None else name - ) - - param_field_val = getattr(param, name) - if not _is_set(param_field_val): - continue - if param_metadata.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[f_name] = ",".join(pp_vals) - elif _is_set(param): - path_param_values[f_name] = _val_to_string(param) - - 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: - for key, value in params.items(): - url_with_params = url_with_params.replace("{" + key + "}", value) - - return url_with_params - - -def remove_suffix(input_string, suffix): - if suffix and input_string.endswith(suffix): - return input_string[: -len(suffix)] - return input_string diff --git a/sync-for-payables/src/codat_sync_for_payables/utils/values.py b/sync-for-payables/src/codat_sync_for_payables/utils/values.py deleted file mode 100644 index dae01a443..000000000 --- a/sync-for-payables/src/codat_sync_for_payables/utils/values.py +++ /dev/null @@ -1,137 +0,0 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from datetime import datetime -from enum import Enum -from email.message import Message -from functools import partial -import os -from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar, Union, cast - -from httpx import Response -from pydantic import BaseModel -from pydantic.fields import FieldInfo - -from ..types.basemodel import Unset - -from .serializers import marshal_json - -from .metadata import ParamMetadata, find_field_metadata - - -def match_content_type(content_type: str, pattern: str) -> bool: - if pattern in (content_type, "*", "*/*"): - return True - - msg = Message() - msg["content-type"] = content_type - media_type = msg.get_content_type() - - if media_type == pattern: - return True - - parts = media_type.split("/") - if len(parts) == 2: - 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: - if "default" in status_codes: - return True - - 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 - - -T = TypeVar("T") - -def cast_partial(typ): - return partial(cast, typ) - -def get_global_from_env( - value: Optional[T], env_key: str, type_cast: Callable[[str], T] -) -> Optional[T]: - if value is not None: - return value - env_value = os.getenv(env_key) - if env_value is not None: - try: - return type_cast(env_value) - except ValueError: - pass - return None - - -def match_response( - response: Response, code: Union[str, List[str]], content_type: str -) -> bool: - codes = code if isinstance(code, list) else [code] - return match_status_codes(codes, response.status_code) and match_content_type( - response.headers.get("content-type", "application/octet-stream"), content_type - ) - - -def _populate_from_globals( - param_name: str, value: Any, param_metadata_type: type, gbls: Any -) -> Tuple[Any, bool]: - if gbls is None: - return value, False - - if not isinstance(gbls, BaseModel): - raise TypeError("globals must be a pydantic model") - - global_fields: Dict[str, FieldInfo] = gbls.__class__.model_fields - found = False - for name in global_fields: - field = global_fields[name] - if name is not param_name: - continue - - found = True - - if value is not None: - return value, True - - global_value = getattr(gbls, name) - - param_metadata = find_field_metadata(field, param_metadata_type) - if param_metadata is None: - return value, True - - return global_value, True - - return value, found - - -def _val_to_string(val) -> str: - if isinstance(val, bool): - return str(val).lower() - if isinstance(val, datetime): - return str(val.isoformat().replace("+00:00", "Z")) - if isinstance(val, Enum): - return str(val.value) - - return str(val) - - -def _get_serialized_params( - metadata: ParamMetadata, field_name: str, obj: Any, typ: type -) -> Dict[str, str]: - params: Dict[str, str] = {} - - serialization = metadata.serialization - if serialization == "json": - params[field_name] = marshal_json(obj, typ) - - return params - - -def _is_set(value: Any) -> bool: - return value is not None and not isinstance(value, Unset)