From 9c7d500e95809902c434994920f770fb84c7c271 Mon Sep 17 00:00:00 2001 From: codat-sdk-codegen Date: Fri, 7 Aug 2026 11:56:01 +0000 Subject: [PATCH] sync-for-expenses: regenerate with the in-house pipeline @ b5f2513, version 8.0.1 -> 8.0.2 --- sync-for-expenses/RELEASES.md | 12 +- sync-for-expenses/USAGE.md | 98 +- .../docs/models/errors/errormessage.md | 30 +- .../models/operations/createaccountrequest.md | 22 +- .../createadjustmenttransactionrequest.md | 16 +- .../operations/createbankaccountrequest.md | 24 +- .../models/operations/createcompanyrequest.md | 8 + .../operations/createconnectionrequest.md | 16 +- .../operations/createconnectionrequestbody.md | 16 +- .../operations/createcustomerrequest.md | 22 +- .../createexpensetransactionrequest.md | 16 +- .../createpartnerexpenseconnectionrequest.md | 14 +- ...tereimbursableexpensetransactionrequest.md | 16 +- .../operations/createsupplierrequest.md | 24 +- .../createtransfertransactionrequest.md | 20 +- .../models/operations/deletecompanyrequest.md | 14 +- .../operations/deleteconnectionrequest.md | 16 +- .../getcompanyconfigurationrequest.md | 14 +- .../operations/getcompanyinforequest.md | 14 +- .../models/operations/getcompanyrequest.md | 14 +- .../models/operations/getconnectionrequest.md | 16 +- .../getcreatebankaccountsmodelrequest.md | 16 +- .../getcreatechartofaccountsmodelrequest.md | 16 +- .../models/operations/getcustomerrequest.md | 16 +- .../operations/getdatastatusdatastatuses.md | 59 +- .../models/operations/getdatastatusrequest.md | 14 +- .../getlastsuccessfulsyncrequest.md | 14 +- .../models/operations/getlatestsyncrequest.md | 14 +- .../operations/getmappingoptionsrequest.md | 14 +- .../operations/getpulloperationrequest.md | 16 +- .../operations/getpushoperationrequest.md | 16 +- .../models/operations/getsupplierrequest.md | 16 +- .../models/operations/getsyncbyidrequest.md | 16 +- .../operations/getsynctransactionrequest.md | 18 +- .../models/operations/listcompaniesrequest.md | 22 +- .../operations/listconnectionsrequest.md | 22 +- .../models/operations/listcustomersrequest.md | 22 +- .../operations/listpulloperationsrequest.md | 22 +- .../operations/listpushoperationsrequest.md | 22 +- .../models/operations/listsuppliersrequest.md | 22 +- .../models/operations/listsyncsrequest.md | 14 +- .../operations/listsynctransactionsrequest.md | 20 +- .../operations/refreshalldatatypesrequest.md | 14 +- .../operations/refreshdatatyperequest.md | 18 +- .../operations/replacecompanyrequest.md | 18 +- .../setcompanyconfigurationrequest.md | 16 +- .../operations/unlinkconnectionrequest.md | 20 +- .../unlinkconnectionupdateconnection.md | 15 +- .../models/operations/updatecompanyrequest.md | 18 +- .../operations/updatecustomerrequest.md | 26 +- .../updateexpensetransactionrequest.md | 20 +- ...tereimbursableexpensetransactionrequest.md | 20 +- .../operations/updatesupplierrequest.md | 28 +- .../uploadexpenseattachmentrequest.md | 20 +- .../{accountingaccount.md => account.md} | 102 +- .../docs/models/shared/accountingaddress.md | 26 +- .../models/shared/accountingaddresstype.md | 36 +- .../docs/models/shared/accountingcustomer.md | 31 - .../docs/models/shared/accountingsupplier.md | 27 - .../docs/models/shared/accountmappinginfo.md | 31 +- .../shared/accountmappinginfoaccounttype.md | 40 +- .../docs/models/shared/accountprototype.md | 36 +- .../docs/models/shared/accountreference.md | 18 +- ...countreference.md => accountreference1.md} | 16 +- .../docs/models/shared/accountstatus.md | 40 +- .../docs/models/shared/accounttype.md | 44 +- .../shared/adjustmenttransactionline.md | 22 +- .../shared/adjustmenttransactionrequest.md | 26 +- .../shared/adjustmenttransactionresponse.md | 14 +- .../docs/models/shared/apaccountref.md | 14 +- .../docs/models/shared/attachment.md | 18 +- .../docs/models/shared/attachmentupload.md | 14 +- .../docs/models/shared/bankaccount.md | 76 +- .../docs/models/shared/bankaccountdetails.md | 14 +- ...bankaccount.md => bankaccountprototype.md} | 60 +- .../models/shared/bankaccountreference.md | 18 +- .../docs/models/shared/bankaccountstatus.md | 38 +- .../docs/models/shared/bankaccounttype.md | 42 +- .../models/shared/clientratelimitwebhook.md | 22 +- .../shared/clientratelimitwebhookpayload.md | 20 +- .../docs/models/shared/codatfile.md | 20 +- .../docs/models/shared/companies.md | 22 +- .../docs/models/shared/company.md | 50 +- .../models/shared/companyconfiguration.md | 18 +- .../docs/models/shared/companydetails.md | 18 + .../docs/models/shared/companyinformation.md | 54 +- .../shared/companyinformationschemastype.md | 38 +- .../models/shared/companyinformationtype.md | 40 +- .../docs/models/shared/companyreference.md | 22 +- .../models/shared/companyreferencelinks.md | 18 +- .../docs/models/shared/companyrequestbody.md | 18 +- .../docs/models/shared/companysyncstatus.md | 31 +- .../models/shared/companyupdaterequest.md | 18 +- .../docs/models/shared/connection.md | 61 +- .../docs/models/shared/connections.md | 22 +- .../docs/models/shared/contact.md | 26 +- .../models/shared/createaccountresponse.md | 42 +- .../shared/createaccountresponseallofdata.md | 23 + .../shared/createaccountresponsemetadata.md | 8 - ...createaccountresponsevaliddatatypelinks.md | 50 - .../shared/createbankaccountresponse.md | 42 +- .../createbankaccountresponseallofdata.md | 24 + ...reatebankaccountresponsebankaccounttype.md | 38 +- .../models/shared/createconnectionrequest.md | 8 + .../models/shared/createcustomerresponse.md | 42 +- .../shared/createcustomerresponseallofdata.md | 22 + .../models/shared/createexpenseresponse.md | 14 +- .../createreimbursableexpenseresponse.md | 14 +- .../models/shared/createsupplierresponse.md | 42 +- .../shared/createsupplierresponseallofdata.md | 21 + .../docs/models/shared/currentstatus.md | 36 + .../docs/models/shared/customer.md | 56 +- .../docs/models/shared/customerdetails.md | 14 +- .../docs/models/shared/customers.md | 22 +- .../docs/models/shared/customerstatus.md | 36 +- .../docs/models/shared/dataconnectionerror.md | 26 +- .../models/shared/dataconnectionstatus.md | 40 +- .../docs/models/shared/datasetstatus.md | 74 +- .../docs/models/shared/datastatus.md | 28 +- .../docs/models/shared/datastatuses.md | 50 + .../docs/models/shared/datatype.md | 135 +- .../docs/models/shared/datatypes.md | 118 +- .../docs/models/shared/errormessage.md | 14 + .../docs/models/shared/errorstatus.md | 36 +- .../docs/models/shared/errorvalidation.md | 18 +- .../docs/models/shared/errorvalidationitem.md | 18 +- .../docs/models/shared/expensecontactref.md | 16 +- .../models/shared/expensecontactreftype.md | 34 +- .../docs/models/shared/expensessyncwebhook.md | 22 +- .../shared/expensessyncwebhookpayload.md | 18 +- .../shared/expensessyncwebhookstatus.md | 20 + .../docs/models/shared/expensetransaction.md | 36 +- .../models/shared/expensetransactionline.md | 28 +- .../models/shared/expensetransactiontype.md | 38 +- .../docs/models/shared/halref.md | 14 +- .../docs/models/shared/integrationtype.md | 36 +- .../docs/models/shared/invoiceto.md | 20 +- .../docs/models/shared/invoicetotype.md | 32 +- .../docs/models/shared/itemref.md | 14 +- sync-for-expenses/docs/models/shared/items.md | 28 +- sync-for-expenses/docs/models/shared/links.md | 20 +- .../docs/models/shared/mappingoptions.md | 21 +- .../docs/models/shared/metadata.md | 14 +- .../docs/models/shared/model3.md | 9 + .../docs/models/shared/paginginfo.md | 11 + sync-for-expenses/docs/models/shared/phone.md | 9 - .../docs/models/shared/phonenumberitems.md | 16 +- .../models/shared/phonenumberitemstype.md | 20 + .../docs/models/shared/pulloperation.md | 44 +- .../docs/models/shared/pulloperations.md | 22 +- .../docs/models/shared/pushchangetype.md | 42 +- .../docs/models/shared/pushfieldvalidation.md | 19 +- .../docs/models/shared/pushoperation.md | 40 +- .../docs/models/shared/pushoperationchange.md | 20 +- .../docs/models/shared/pushoperationref.md | 19 +- .../docs/models/shared/pushoperations.md | 22 +- .../docs/models/shared/pushoperationstatus.md | 40 +- .../docs/models/shared/pushoption.md | 26 +- .../docs/models/shared/pushoptionchoice.md | 22 +- .../docs/models/shared/pushoptionproperty.md | 26 +- .../docs/models/shared/pushoptiontype.md | 46 +- .../docs/models/shared/pushvalidationinfo.md | 17 +- .../docs/models/shared/recordref.md | 14 +- .../shared/reimbursableexpensetransaction.md | 32 +- .../reimbursableexpensetransactionline.md | 30 +- .../models/shared/reimbursementcontactref.md | 14 +- .../docs/models/shared/schemadatatype.md | 118 +- .../docs/models/shared/schematransaction.md | 21 +- .../docs/models/shared/security.md | 16 +- .../docs/models/shared/sourcetype.md | 46 +- .../docs/models/shared/status.md | 72 +- .../docs/models/shared/supplementaldata.md | 24 +- .../docs/models/shared/supplier.md | 48 +- .../docs/models/shared/supplierdetails.md | 14 +- .../docs/models/shared/suppliers.md | 22 +- .../docs/models/shared/supplierstatus.md | 36 +- .../docs/models/shared/synccompletewebhook.md | 17 + .../models/shared/synccompletewebhookdata.md | 9 + .../docs/models/shared/syncfailedwebhook.md | 17 + .../models/shared/syncfailedwebhookdata.md | 10 + .../docs/models/shared/syncinitiated.md | 9 + .../docs/models/shared/taxratemappinginfo.md | 25 +- sync-for-expenses/docs/models/shared/to.md | 9 - .../shared/trackingcategorymappinginfo.md | 21 +- .../docs/models/shared/trackingref.md | 16 +- .../trackingrefadjustmenttransaction.md | 16 +- ...rackingrefadjustmenttransactiondatatype.md | 36 +- .../docs/models/shared/trackingrefdatatype.md | 34 +- .../docs/models/shared/transaction.md | 18 +- .../shared/transactiondefinitionsstatus.md | 42 +- .../docs/models/shared/transactions.md | 23 +- .../docs/models/shared/transactionstatus.md | 42 +- .../shared/transfertransactionrequest.md | 22 +- ..._.md => transfertransactionrequestfrom.md} | 16 +- .../shared/transfertransactionrequestto.md | 9 + .../shared/transfertransactionresponse.md | 14 +- sync-for-expenses/docs/models/shared/type.md | 40 +- .../docs/models/shared/updateconnection.md | 9 + .../models/shared/updatecustomerresponse.md | 42 +- ...pdatecustomerresponseaccountingcustomer.md | 31 - .../shared/updatecustomerresponseallofdata.md | 22 + .../models/shared/updateexpenserequest.md | 30 +- ...pdateexpenserequestbankaccountreference.md | 8 - .../models/shared/updateexpenserequesttype.md | 38 +- .../models/shared/updateexpenseresponse.md | 14 +- ...tereimbursableexpensetransactionrequest.md | 30 +- .../models/shared/updatesupplierresponse.md | 42 +- ...pdatesupplierresponseaccountingsupplier.md | 27 - .../shared/updatesupplierresponseallofdata.md | 21 + .../docs/models/shared/validation.md | 20 +- .../docs/models/shared/validationitem.md | 19 +- .../docs/models/shared/validdatatypelinks.md | 98 +- .../docs/models/shared/validfor.md | 42 +- .../models/shared/validtransactiontypes.md | 36 +- .../docs/models/shared/weblink.md | 20 +- .../docs/models/utils/retryconfig.md | 46 +- .../docs/sdks/accounts/README.md | 668 ++--- .../docs/sdks/adjustments/README.md | 271 +- .../docs/sdks/attachments/README.md | 144 +- .../docs/sdks/bankaccounts/README.md | 734 +++--- .../docs/sdks/companies/README.md | 1136 ++++---- .../docs/sdks/companyinfo/README.md | 108 +- .../docs/sdks/configuration/README.md | 214 +- .../docs/sdks/connections/README.md | 640 +++-- .../docs/sdks/customers/README.md | 2087 ++++++++------- .../docs/sdks/expenses/README.md | 708 ++--- .../docs/sdks/managedata/README.md | 493 ++-- .../docs/sdks/mappingoptions/README.md | 108 +- .../docs/sdks/pushoperations/README.md | 207 +- .../docs/sdks/reimbursements/README.md | 660 ++--- .../docs/sdks/suppliers/README.md | 2312 ++++++++--------- sync-for-expenses/docs/sdks/sync/README.md | 392 +-- .../docs/sdks/transactionstatus/README.md | 208 +- .../docs/sdks/transfers/README.md | 310 +-- sync-for-expenses/pyproject.toml | 55 +- .../src/codat_sync_for_expenses/__init__.py | 196 +- .../_hooks/__init__.py | 31 +- .../_hooks/sdkhooks.py | 111 +- .../codat_sync_for_expenses/_hooks/types.py | 68 +- .../_httpx_transport.py | 130 + .../src/codat_sync_for_expenses/_version.py | 15 +- .../src/codat_sync_for_expenses/accounts.py | 448 +--- .../codat_sync_for_expenses/adjustments.py | 250 +- .../codat_sync_for_expenses/api/__init__.py | 22 + .../codat_sync_for_expenses/api/accounts.py | 519 ++++ .../api/adjustments.py | 282 ++ .../api/attachments.py | 300 +++ .../api/bank_accounts.py | 519 ++++ .../codat_sync_for_expenses/api/companies.py | 1391 ++++++++++ .../api/company_info.py | 261 ++ .../api/configuration.py | 489 ++++ .../api/connections.py | 1396 ++++++++++ .../codat_sync_for_expenses/api/customers.py | 1027 ++++++++ .../codat_sync_for_expenses/api/expenses.py | 519 ++++ .../api/manage_data.py | 1156 +++++++++ .../api/mapping_options.py | 260 ++ .../api/push_operations.py | 510 ++++ .../api/reimbursements.py | 517 ++++ .../codat_sync_for_expenses/api/suppliers.py | 1027 ++++++++ .../src/codat_sync_for_expenses/api/sync.py | 899 +++++++ .../api/transaction_status.py | 506 ++++ .../codat_sync_for_expenses/api/transfers.py | 287 ++ .../src/codat_sync_for_expenses/api_client.py | 803 ++++++ .../codat_sync_for_expenses/api_response.py | 21 + .../codat_sync_for_expenses/attachments.py | 262 +- .../codat_sync_for_expenses/bank_accounts.py | 452 +--- .../src/codat_sync_for_expenses/basesdk.py | 393 --- .../src/codat_sync_for_expenses/companies.py | 1286 +-------- .../codat_sync_for_expenses/company_info.py | 210 +- .../codat_sync_for_expenses/configuration.py | 1005 ++++--- .../codat_sync_for_expenses/connections.py | 1228 +-------- .../src/codat_sync_for_expenses/customers.py | 868 +------ .../src/codat_sync_for_expenses/exceptions.py | 200 ++ .../src/codat_sync_for_expenses/expenses.py | 520 +--- .../codat_sync_for_expenses/manage_data.py | 1010 +------ .../mapping_options.py | 212 +- .../models/__init__.py | 154 +- .../models/_compat/__init__.py | 3 + .../models/_compat/companyinformation.py | 10 + .../models/_compat/expensecontactref.py | 8 + .../models/_compat/schema_datatype.py | 50 + .../models/_compat/transaction.py | 12 + .../codat_sync_for_expenses/models/account.py | 164 ++ .../account_mapping_info_account_type.py | 12 + .../models/account_reference.py | 99 + .../models/account_reference1.py | 99 + .../models/accounting_address.py | 123 + .../models/bank_account_prototype.py | 146 ++ .../models/bank_account_reference.py | 99 + .../models/bank_account_type.py | 10 + .../models/company_details.py | 141 + .../models/company_information.py | 171 ++ .../models/company_information_type.py | 10 + .../models/company_reference_links.py | 99 + .../create_account_response_all_of_data.py | 164 ++ .../models/create_bank_account_response.py | 171 ++ ...reate_bank_account_response_all_of_data.py | 170 ++ .../models/create_connection_request.py | 110 + .../create_customer_response_all_of_data.py | 166 ++ .../create_supplier_response_all_of_data.py | 155 ++ .../models/current_status.py | 28 + .../models/data_statuses.py | 362 +++ .../models/data_types.py | 50 + .../models/dataset_status.py | 28 + .../models/error_message.py | 121 + .../models/error_status.py | 9 + .../models/errors/__init__.py | 35 +- .../models/errors/codatsyncexpenseserror.py | 74 +- .../models/errors/errormessage.py | 76 +- .../models/errors/no_response_error.py | 11 +- .../models/errors/responsevalidationerror.py | 45 +- .../models/errors/sdkerror.py | 55 +- .../models/expense_contact_ref.py | 114 + .../models/expense_transaction_type.py | 11 + .../models/expenses_sync_webhook_status.py | 12 + .../models/invoice_to_type.py | 8 + .../codat_sync_for_expenses/models/model3.py | 102 + .../models/operations/__init__.py | 506 ++-- .../models/operations/create_account.py | 84 +- .../create_adjustment_transaction.py | 58 +- .../models/operations/create_bank_account.py | 97 +- .../models/operations/create_connection.py | 85 +- .../models/operations/create_customer.py | 97 +- .../operations/create_expense_transaction.py | 56 +- .../create_partner_expense_connection.py | 23 +- ...create_reimbursable_expense_transaction.py | 60 +- .../models/operations/create_supplier.py | 97 +- .../operations/create_transfer_transaction.py | 65 +- .../models/operations/delete_company.py | 23 +- .../models/operations/delete_connection.py | 32 +- .../models/operations/get_company.py | 23 +- .../operations/get_company_configuration.py | 23 +- .../models/operations/get_company_info.py | 23 +- .../models/operations/get_connection.py | 32 +- .../get_create_bankaccounts_model.py | 32 +- .../get_create_chartofaccounts_model.py | 32 +- .../models/operations/get_customer.py | 32 +- .../models/operations/get_data_status.py | 404 +-- .../operations/get_last_successful_sync.py | 23 +- .../models/operations/get_latest_sync.py | 23 +- .../models/operations/get_mapping_options.py | 23 +- .../models/operations/get_pull_operation.py | 32 +- .../models/operations/get_push_operation.py | 32 +- .../models/operations/get_supplier.py | 32 +- .../models/operations/get_sync_by_id.py | 32 +- .../models/operations/get_sync_transaction.py | 41 +- .../models/operations/list_companies.py | 74 +- .../models/operations/list_connections.py | 79 +- .../models/operations/list_customers.py | 79 +- .../models/operations/list_pull_operations.py | 79 +- .../models/operations/list_push_operations.py | 79 +- .../models/operations/list_suppliers.py | 79 +- .../operations/list_sync_transactions.py | 71 +- .../models/operations/list_syncs.py | 23 +- .../operations/refresh_all_data_types.py | 23 +- .../models/operations/refresh_data_type.py | 66 +- .../models/operations/replace_company.py | 56 +- .../operations/set_company_configuration.py | 56 +- .../models/operations/unlink_connection.py | 91 +- .../models/operations/update_company.py | 56 +- .../models/operations/update_customer.py | 115 +- .../operations/update_expense_transaction.py | 65 +- ...update_reimbursable_expense_transaction.py | 67 +- .../models/operations/update_supplier.py | 115 +- .../operations/upload_expense_attachment.py | 72 +- .../models/paging_info.py | 113 + .../models/phone_number_items_type.py | 12 + .../models/shared/__init__.py | 1364 +++++----- .../models/shared/accountingaddresstype.py | 37 +- .../models/shared/accountmappinginfo.py | 278 +- .../models/shared/accountprototype.py | 439 +--- .../models/shared/accountstatus.py | 39 +- .../models/shared/accounttype.py | 45 +- .../shared/adjustmenttransactionline.py | 201 +- .../shared/adjustmenttransactionrequest.py | 295 +-- .../shared/adjustmenttransactionresponse.py | 111 +- .../models/shared/apaccountref.py | 108 +- .../models/shared/attachment.py | 127 +- .../models/shared/attachmentupload.py | 35 +- .../models/shared/bankaccount.py | 425 ++- .../models/shared/bankaccountdetails.py | 108 +- .../models/shared/bankaccountstatus.py | 39 +- .../models/shared/clientratelimitwebhook.py | 155 +- .../shared/clientratelimitwebhookpayload.py | 143 +- .../models/shared/codatfile.py | 59 +- .../models/shared/companies.py | 148 +- .../models/shared/company.py | 344 +-- .../models/shared/companyconfiguration.py | 124 +- .../models/shared/companyinformation.py | 483 +--- .../models/shared/companyreference.py | 149 +- .../models/shared/companyrequestbody.py | 130 +- .../models/shared/companysyncstatus.py | 254 +- .../models/shared/companyupdaterequest.py | 133 +- .../models/shared/connection.py | 368 ++- .../models/shared/connections.py | 148 +- .../models/shared/contact.py | 223 +- .../models/shared/createaccountresponse.py | 773 ++---- .../shared/createbankaccountresponse.py | 512 +--- .../models/shared/createcustomerresponse.py | 538 ++-- .../models/shared/createexpenseresponse.py | 111 +- .../createreimbursableexpenseresponse.py | 111 +- .../models/shared/createsupplierresponse.py | 511 ++-- .../models/shared/customer.py | 329 ++- .../models/shared/customerdetails.py | 108 +- .../models/shared/customers.py | 149 +- .../models/shared/customerstatus.py | 37 +- .../models/shared/dataconnectionerror.py | 253 +- .../models/shared/dataconnectionstatus.py | 39 +- .../models/shared/datastatus.py | 240 +- .../models/shared/datatype.py | 134 +- .../models/shared/errorvalidation.py | 154 +- .../models/shared/errorvalidationitem.py | 156 +- .../models/shared/expensecontactref.py | 43 +- .../models/shared/expensessyncwebhook.py | 155 +- .../shared/expensessyncwebhookpayload.py | 137 +- .../models/shared/expensetransaction.py | 409 ++- .../models/shared/expensetransactionline.py | 238 +- .../models/shared/halref.py | 108 +- .../models/shared/integrationtype.py | 35 +- .../models/shared/invoiceto.py | 130 +- .../models/shared/itemref.py | 108 +- .../models/shared/items.py | 186 +- .../models/shared/links.py | 137 +- .../models/shared/mappingoptions.py | 218 +- .../models/shared/metadata.py | 142 +- .../models/shared/phonenumber_items.py | 155 +- .../models/shared/pulloperation.py | 338 +-- .../models/shared/pulloperations.py | 148 +- .../models/shared/pushchangetype.py | 40 +- .../models/shared/pushfieldvalidation.py | 163 +- .../models/shared/pushoperation.py | 353 ++- .../models/shared/pushoperationchange.py | 164 +- .../models/shared/pushoperationref.py | 145 +- .../models/shared/pushoperations.py | 148 +- .../models/shared/pushoperationstatus.py | 38 +- .../models/shared/pushoption.py | 202 +- .../models/shared/pushoptionchoice.py | 140 +- .../models/shared/pushoptionproperty.py | 200 +- .../models/shared/pushoptiontype.py | 48 +- .../models/shared/pushvalidationinfo.py | 168 +- .../models/shared/recordref.py | 108 +- .../shared/reimbursableexpensetransaction.py | 376 +-- .../reimbursableexpensetransactionline.py | 247 +- .../models/shared/reimbursementcontactref.py | 102 +- .../models/shared/schema_datatype.py | 50 +- .../models/shared/schema_transaction.py | 182 +- .../models/shared/security.py | 24 +- .../models/shared/status.py | 74 +- .../models/shared/supplementaldata.py | 136 +- .../models/shared/supplier.py | 289 +-- .../models/shared/supplierdetails.py | 108 +- .../models/shared/suppliers.py | 149 +- .../models/shared/supplierstatus.py | 37 +- .../models/shared/taxratemappinginfo.py | 240 +- .../shared/trackingcategorymappinginfo.py | 177 +- .../models/shared/trackingref.py | 134 +- .../trackingrefadjustmenttransaction.py | 136 +- .../models/shared/transaction.py | 76 +- .../models/shared/transactions.py | 162 +- .../models/shared/transactionstatus.py | 40 +- .../shared/transfertransactionrequest.py | 215 +- .../shared/transfertransactionresponse.py | 111 +- .../models/shared/updatecustomerresponse.py | 538 ++-- .../models/shared/updateexpenserequest.py | 347 +-- .../models/shared/updateexpenseresponse.py | 111 +- ...tereimbursableexpensetransactionrequest.py | 370 +-- .../models/shared/updatesupplierresponse.py | 511 ++-- .../models/shared/validation.py | 154 +- .../models/shared/validationitem.py | 170 +- .../models/shared/validfor.py | 18 +- .../models/shared/validtransactiontypes.py | 12 +- .../models/source_type.py | 14 + .../models/sync_complete_webhook.py | 124 + .../models/sync_complete_webhook_data.py | 102 + .../models/sync_failed_webhook.py | 124 + .../models/sync_failed_webhook_data.py | 105 + .../models/sync_initiated.py | 113 + ...ng_ref_adjustment_transaction_data_type.py | 10 + .../models/tracking_ref_data_type.py | 9 + .../models/transaction.py | 122 + .../transfer_transaction_request_from.py | 108 + .../models/transfer_transaction_request_to.py | 108 + .../codat_sync_for_expenses/models/type.py | 12 + .../models/update_connection.py | 114 + .../update_customer_response_all_of_data.py | 166 ++ .../models/update_expense_request_type.py | 11 + .../update_supplier_response_all_of_data.py | 155 ++ .../models/valid_data_type_links.py | 107 + .../codat_sync_for_expenses/models/weblink.py | 114 + .../push_operations.py | 408 +-- .../src/codat_sync_for_expenses/py.typed | 1 - .../codat_sync_for_expenses/reimbursements.py | 504 +--- .../src/codat_sync_for_expenses/rest.py | 258 ++ .../src/codat_sync_for_expenses/sdk.py | 420 ++- .../sdkconfiguration.py | 48 - .../src/codat_sync_for_expenses/suppliers.py | 966 +------ .../src/codat_sync_for_expenses/sync.py | 794 +----- .../transaction_status.py | 408 +-- .../src/codat_sync_for_expenses/transfers.py | 262 +- .../codat_sync_for_expenses/types/__init__.py | 73 +- .../types/basemodel.py | 77 - .../codat_sync_for_expenses/utils/__init__.py | 176 +- .../utils/annotations.py | 79 - .../utils/datetimes.py | 23 - .../utils/dynamic_imports.py | 54 - .../codat_sync_for_expenses/utils/enums.py | 134 - .../utils/eventstreaming.py | 309 --- .../codat_sync_for_expenses/utils/forms.py | 234 -- .../codat_sync_for_expenses/utils/headers.py | 136 - .../codat_sync_for_expenses/utils/logger.py | 22 - .../codat_sync_for_expenses/utils/metadata.py | 119 - .../utils/queryparams.py | 217 -- .../utils/requestbodies.py | 66 - .../codat_sync_for_expenses/utils/retries.py | 343 +-- .../codat_sync_for_expenses/utils/security.py | 198 -- .../utils/serializers.py | 205 +- .../utils/unmarshal_json_response.py | 38 - .../src/codat_sync_for_expenses/utils/url.py | 155 -- .../codat_sync_for_expenses/utils/values.py | 137 - .../codatsyncexpenses/_hooks/registration.py | 13 - 520 files changed, 38650 insertions(+), 36498 deletions(-) create mode 100644 sync-for-expenses/docs/models/operations/createcompanyrequest.md rename sync-for-expenses/docs/models/shared/{accountingaccount.md => account.md} (96%) delete mode 100644 sync-for-expenses/docs/models/shared/accountingcustomer.md delete mode 100644 sync-for-expenses/docs/models/shared/accountingsupplier.md rename sync-for-expenses/docs/models/shared/{transfertransactionrequestaccountreference.md => accountreference1.md} (81%) rename sync-for-expenses/docs/models/shared/{accountingbankaccount.md => bankaccountprototype.md} (70%) create mode 100644 sync-for-expenses/docs/models/shared/companydetails.md create mode 100644 sync-for-expenses/docs/models/shared/createaccountresponseallofdata.md delete mode 100644 sync-for-expenses/docs/models/shared/createaccountresponsemetadata.md delete mode 100644 sync-for-expenses/docs/models/shared/createaccountresponsevaliddatatypelinks.md create mode 100644 sync-for-expenses/docs/models/shared/createbankaccountresponseallofdata.md create mode 100644 sync-for-expenses/docs/models/shared/createconnectionrequest.md create mode 100644 sync-for-expenses/docs/models/shared/createcustomerresponseallofdata.md create mode 100644 sync-for-expenses/docs/models/shared/createsupplierresponseallofdata.md create mode 100644 sync-for-expenses/docs/models/shared/currentstatus.md create mode 100644 sync-for-expenses/docs/models/shared/datastatuses.md create mode 100644 sync-for-expenses/docs/models/shared/errormessage.md create mode 100644 sync-for-expenses/docs/models/shared/expensessyncwebhookstatus.md create mode 100644 sync-for-expenses/docs/models/shared/model3.md create mode 100644 sync-for-expenses/docs/models/shared/paginginfo.md delete mode 100644 sync-for-expenses/docs/models/shared/phone.md create mode 100644 sync-for-expenses/docs/models/shared/phonenumberitemstype.md create mode 100644 sync-for-expenses/docs/models/shared/synccompletewebhook.md create mode 100644 sync-for-expenses/docs/models/shared/synccompletewebhookdata.md create mode 100644 sync-for-expenses/docs/models/shared/syncfailedwebhook.md create mode 100644 sync-for-expenses/docs/models/shared/syncfailedwebhookdata.md create mode 100644 sync-for-expenses/docs/models/shared/syncinitiated.md delete mode 100644 sync-for-expenses/docs/models/shared/to.md rename sync-for-expenses/docs/models/shared/{from_.md => transfertransactionrequestfrom.md} (90%) create mode 100644 sync-for-expenses/docs/models/shared/transfertransactionrequestto.md create mode 100644 sync-for-expenses/docs/models/shared/updateconnection.md delete mode 100644 sync-for-expenses/docs/models/shared/updatecustomerresponseaccountingcustomer.md create mode 100644 sync-for-expenses/docs/models/shared/updatecustomerresponseallofdata.md delete mode 100644 sync-for-expenses/docs/models/shared/updateexpenserequestbankaccountreference.md delete mode 100644 sync-for-expenses/docs/models/shared/updatesupplierresponseaccountingsupplier.md create mode 100644 sync-for-expenses/docs/models/shared/updatesupplierresponseallofdata.md create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/_httpx_transport.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/api/__init__.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/api/accounts.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/api/adjustments.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/api/attachments.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/api/bank_accounts.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/api/companies.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/api/company_info.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/api/configuration.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/api/connections.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/api/customers.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/api/expenses.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/api/manage_data.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/api/mapping_options.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/api/push_operations.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/api/reimbursements.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/api/suppliers.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/api/sync.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/api/transaction_status.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/api/transfers.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/api_client.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/api_response.py delete mode 100644 sync-for-expenses/src/codat_sync_for_expenses/basesdk.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/exceptions.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/_compat/__init__.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/_compat/companyinformation.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/_compat/expensecontactref.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/_compat/schema_datatype.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/_compat/transaction.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/account.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/account_mapping_info_account_type.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/account_reference.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/account_reference1.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/accounting_address.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/bank_account_prototype.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/bank_account_reference.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/bank_account_type.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/company_details.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/company_information.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/company_information_type.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/company_reference_links.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/create_account_response_all_of_data.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/create_bank_account_response.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/create_bank_account_response_all_of_data.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/create_connection_request.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/create_customer_response_all_of_data.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/create_supplier_response_all_of_data.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/current_status.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/data_statuses.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/data_types.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/dataset_status.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/error_message.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/error_status.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/expense_contact_ref.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/expense_transaction_type.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/expenses_sync_webhook_status.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/invoice_to_type.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/model3.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/paging_info.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/phone_number_items_type.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/source_type.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/sync_complete_webhook.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/sync_complete_webhook_data.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/sync_failed_webhook.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/sync_failed_webhook_data.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/sync_initiated.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/tracking_ref_adjustment_transaction_data_type.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/tracking_ref_data_type.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/transaction.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/transfer_transaction_request_from.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/transfer_transaction_request_to.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/type.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/update_connection.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/update_customer_response_all_of_data.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/update_expense_request_type.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/update_supplier_response_all_of_data.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/valid_data_type_links.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/models/weblink.py create mode 100644 sync-for-expenses/src/codat_sync_for_expenses/rest.py delete mode 100644 sync-for-expenses/src/codat_sync_for_expenses/sdkconfiguration.py delete mode 100644 sync-for-expenses/src/codat_sync_for_expenses/types/basemodel.py delete mode 100644 sync-for-expenses/src/codat_sync_for_expenses/utils/annotations.py delete mode 100644 sync-for-expenses/src/codat_sync_for_expenses/utils/datetimes.py delete mode 100644 sync-for-expenses/src/codat_sync_for_expenses/utils/dynamic_imports.py delete mode 100644 sync-for-expenses/src/codat_sync_for_expenses/utils/enums.py delete mode 100644 sync-for-expenses/src/codat_sync_for_expenses/utils/eventstreaming.py delete mode 100644 sync-for-expenses/src/codat_sync_for_expenses/utils/forms.py delete mode 100644 sync-for-expenses/src/codat_sync_for_expenses/utils/headers.py delete mode 100644 sync-for-expenses/src/codat_sync_for_expenses/utils/logger.py delete mode 100644 sync-for-expenses/src/codat_sync_for_expenses/utils/metadata.py delete mode 100644 sync-for-expenses/src/codat_sync_for_expenses/utils/queryparams.py delete mode 100644 sync-for-expenses/src/codat_sync_for_expenses/utils/requestbodies.py delete mode 100644 sync-for-expenses/src/codat_sync_for_expenses/utils/security.py delete mode 100644 sync-for-expenses/src/codat_sync_for_expenses/utils/unmarshal_json_response.py delete mode 100644 sync-for-expenses/src/codat_sync_for_expenses/utils/url.py delete mode 100644 sync-for-expenses/src/codat_sync_for_expenses/utils/values.py delete mode 100644 sync-for-expenses/src/codatsyncexpenses/_hooks/registration.py diff --git a/sync-for-expenses/RELEASES.md b/sync-for-expenses/RELEASES.md index 3678c7f42..635d6c2d0 100644 --- a/sync-for-expenses/RELEASES.md +++ b/sync-for-expenses/RELEASES.md @@ -766,4 +766,14 @@ Based on: ### Generated - [python v8.0.1] sync-for-expenses ### Releases -- [PyPI v8.0.1] https://pypi.org/project/codat-sync-for-expenses/8.0.1 - sync-for-expenses \ No newline at end of file +- [PyPI v8.0.1] https://pypi.org/project/codat-sync-for-expenses/8.0.1 - sync-for-expenses + +## 2026-08-07 11:56:00 +### Changes +Based on: +- OpenAPI Doc prealpha https://raw.githubusercontent.com/codatio/oas/main/yaml/Codat-Sync-Expenses.yaml +- codat sdk-codegen b5f25135143b1ccfb99c941df11a7a1596dbe31e https://github.com/codat-spikes/sdk-codegen +### Generated +- [python v8.0.2] sync-for-expenses +### Releases +- [PyPI v8.0.2] https://pypi.org/project/codat-sync-for-expenses/8.0.2 - sync-for-expenses diff --git a/sync-for-expenses/USAGE.md b/sync-for-expenses/USAGE.md index 57a78c032..a45d8d2cd 100644 --- a/sync-for-expenses/USAGE.md +++ b/sync-for-expenses/USAGE.md @@ -1,49 +1,51 @@ - -```python -# Synchronous Example -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.companies.create(request={ - "name": "Technicalium", - }) - - # 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_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - -async def main(): - - async with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), - ) as codat_sync_expenses: - - res = await codat_sync_expenses.companies.create_async(request={ - "name": "Technicalium", - }) - - # Handle response - print(res) - -asyncio.run(main()) -``` + +```python +# Synchronous Example +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.companies.create(request={ + "description": "Requested early access to the new financing scheme.", + "name": "Bank of Dave", + }) + + # 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_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + +async def main(): + + async with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), + ) as codat_sync_expenses: + + res = await codat_sync_expenses.companies.create_async(request={ + "description": "Requested early access to the new financing scheme.", + "name": "Bank of Dave", + }) + + # Handle response + print(res) + +asyncio.run(main()) +``` \ No newline at end of file diff --git a/sync-for-expenses/docs/models/errors/errormessage.md b/sync-for-expenses/docs/models/errors/errormessage.md index c24cd9acc..425e22bbf 100644 --- a/sync-for-expenses/docs/models/errors/errormessage.md +++ b/sync-for-expenses/docs/models/errors/errormessage.md @@ -1,16 +1,14 @@ -# ErrorMessage - -Your `query` parameter was not correctly formed - - -## 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` | [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. | \ 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-expenses/docs/models/operations/createaccountrequest.md b/sync-for-expenses/docs/models/operations/createaccountrequest.md index f8733acf4..f7d51cf1e 100644 --- a/sync-for-expenses/docs/models/operations/createaccountrequest.md +++ b/sync-for-expenses/docs/models/operations/createaccountrequest.md @@ -1,12 +1,12 @@ -# CreateAccountRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | -| `account_prototype` | [Optional[shared.AccountPrototype]](../../models/shared/accountprototype.md) | :heavy_minus_sign: | N/A | | -| `allow_sync_on_push_complete` | *Optional[bool]* | :heavy_minus_sign: | Allow a sync upon push completion. | | -| `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 | +# CreateAccountRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | +| `account_prototype` | [Optional[shared.AccountPrototype]](../../models/shared/accountprototype.md) | :heavy_minus_sign: | N/A | | +| `allow_sync_on_push_complete` | *Optional[bool]* | :heavy_minus_sign: | Allow a sync upon push completion. | | +| `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 | | `timeout_in_minutes` | *Optional[int]* | :heavy_minus_sign: | Time limit for the push operation to complete before it is timed out. | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/operations/createadjustmenttransactionrequest.md b/sync-for-expenses/docs/models/operations/createadjustmenttransactionrequest.md index 4fb25bd35..4898e3448 100644 --- a/sync-for-expenses/docs/models/operations/createadjustmenttransactionrequest.md +++ b/sync-for-expenses/docs/models/operations/createadjustmenttransactionrequest.md @@ -1,9 +1,9 @@ -# CreateAdjustmentTransactionRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | -| `request_body` | List[[shared.AdjustmentTransactionRequest](../../models/shared/adjustmenttransactionrequest.md)] | :heavy_minus_sign: | N/A | | +# CreateAdjustmentTransactionRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | +| `request_body` | List[[shared.AdjustmentTransactionRequest](../../models/shared/adjustmenttransactionrequest.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-expenses/docs/models/operations/createbankaccountrequest.md b/sync-for-expenses/docs/models/operations/createbankaccountrequest.md index 0d433a076..7498dbd99 100644 --- a/sync-for-expenses/docs/models/operations/createbankaccountrequest.md +++ b/sync-for-expenses/docs/models/operations/createbankaccountrequest.md @@ -1,12 +1,12 @@ -# CreateBankAccountRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| -------------------------------------------------------------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------------- | -| `bank_account` | [OptionalNullable[shared.BankAccount]](../../models/shared/bankaccount.md) | :heavy_minus_sign: | N/A | | -| `allow_sync_on_push_complete` | *Optional[bool]* | :heavy_minus_sign: | Allow a sync upon push completion. | | -| `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 | -| `timeout_in_minutes` | *Optional[int]* | :heavy_minus_sign: | Time limit for the push operation to complete before it is timed out. | | \ No newline at end of file +# CreateBankAccountRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------------------------------------------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------- | +| `allow_sync_on_push_complete` | *Optional[bool]* | :heavy_minus_sign: | Allow a sync upon push completion. | | +| `bank_account` | [Optional[shared.BankAccount]](../../models/shared/bankaccount.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 | +| `timeout_in_minutes` | *Optional[int]* | :heavy_minus_sign: | Time limit for the push operation to complete before it is timed out. | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/operations/createcompanyrequest.md b/sync-for-expenses/docs/models/operations/createcompanyrequest.md new file mode 100644 index 000000000..ebd7ca0a0 --- /dev/null +++ b/sync-for-expenses/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-expenses/docs/models/operations/createconnectionrequest.md b/sync-for-expenses/docs/models/operations/createconnectionrequest.md index 0998495bf..32316fd7b 100644 --- a/sync-for-expenses/docs/models/operations/createconnectionrequest.md +++ b/sync-for-expenses/docs/models/operations/createconnectionrequest.md @@ -1,9 +1,9 @@ -# CreateConnectionRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | -| `request_body` | [Optional[operations.CreateConnectionRequestBody]](../../models/operations/createconnectionrequestbody.md) | :heavy_minus_sign: | N/A | | +# 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-expenses/docs/models/operations/createconnectionrequestbody.md b/sync-for-expenses/docs/models/operations/createconnectionrequestbody.md index 891314d08..5a6200d18 100644 --- a/sync-for-expenses/docs/models/operations/createconnectionrequestbody.md +++ b/sync-for-expenses/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-expenses/docs/models/operations/createcustomerrequest.md b/sync-for-expenses/docs/models/operations/createcustomerrequest.md index 46669ae4a..a83debe1d 100644 --- a/sync-for-expenses/docs/models/operations/createcustomerrequest.md +++ b/sync-for-expenses/docs/models/operations/createcustomerrequest.md @@ -1,12 +1,12 @@ -# CreateCustomerRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| --------------------------------------------------------------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------- | -| `customer` | [OptionalNullable[shared.Customer]](../../models/shared/customer.md) | :heavy_minus_sign: | N/A | | -| `allow_sync_on_push_complete` | *Optional[bool]* | :heavy_minus_sign: | Allow a sync upon push completion. | | -| `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 | +# CreateCustomerRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------------------------------------------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------- | +| `allow_sync_on_push_complete` | *Optional[bool]* | :heavy_minus_sign: | Allow a sync upon push completion. | | +| `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 | +| `customer` | [Optional[shared.Customer]](../../models/shared/customer.md) | :heavy_minus_sign: | N/A | | | `timeout_in_minutes` | *Optional[int]* | :heavy_minus_sign: | Time limit for the push operation to complete before it is timed out. | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/operations/createexpensetransactionrequest.md b/sync-for-expenses/docs/models/operations/createexpensetransactionrequest.md index 34338390a..be16b960c 100644 --- a/sync-for-expenses/docs/models/operations/createexpensetransactionrequest.md +++ b/sync-for-expenses/docs/models/operations/createexpensetransactionrequest.md @@ -1,9 +1,9 @@ -# CreateExpenseTransactionRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | -| `request_body` | List[[shared.ExpenseTransaction](../../models/shared/expensetransaction.md)] | :heavy_minus_sign: | N/A | | +# CreateExpenseTransactionRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | +| `request_body` | List[[shared.ExpenseTransaction](../../models/shared/expensetransaction.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-expenses/docs/models/operations/createpartnerexpenseconnectionrequest.md b/sync-for-expenses/docs/models/operations/createpartnerexpenseconnectionrequest.md index d1793f934..3c72387ca 100644 --- a/sync-for-expenses/docs/models/operations/createpartnerexpenseconnectionrequest.md +++ b/sync-for-expenses/docs/models/operations/createpartnerexpenseconnectionrequest.md @@ -1,8 +1,8 @@ -# CreatePartnerExpenseConnectionRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +# CreatePartnerExpenseConnectionRequest + + +## 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-expenses/docs/models/operations/createreimbursableexpensetransactionrequest.md b/sync-for-expenses/docs/models/operations/createreimbursableexpensetransactionrequest.md index 7201650d9..b72d77a04 100644 --- a/sync-for-expenses/docs/models/operations/createreimbursableexpensetransactionrequest.md +++ b/sync-for-expenses/docs/models/operations/createreimbursableexpensetransactionrequest.md @@ -1,9 +1,9 @@ -# CreateReimbursableExpenseTransactionRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | -| `request_body` | List[[shared.ReimbursableExpenseTransaction](../../models/shared/reimbursableexpensetransaction.md)] | :heavy_minus_sign: | N/A | | +# CreateReimbursableExpenseTransactionRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | +| `request_body` | List[[shared.ReimbursableExpenseTransaction](../../models/shared/reimbursableexpensetransaction.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-expenses/docs/models/operations/createsupplierrequest.md b/sync-for-expenses/docs/models/operations/createsupplierrequest.md index 914b9f20e..5593a21cd 100644 --- a/sync-for-expenses/docs/models/operations/createsupplierrequest.md +++ b/sync-for-expenses/docs/models/operations/createsupplierrequest.md @@ -1,12 +1,12 @@ -# CreateSupplierRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `supplier` | [OptionalNullable[shared.Supplier]](../../models/shared/supplier.md) | :heavy_minus_sign: | N/A | {
"id": "C520FFD4-F6F6-4FC2-A6D2-5D7088B2B14F",
"supplierName": "Kelly's Industrial Supplies",
"contactName": "Kelly's Industrial Supplies",
"emailAddress": "sales@kellysupplies.com",
"phone": "07999 999999",
"addresses": [
{
"type": "Billing",
"line1": "Unit 51",
"line2": "Bakersfield Industrial Estate",
"city": "Bakersfield",
"region": "California",
"country": "USA",
"postalcode": "93308"
}
],
"registrationNumber": "string",
"taxNumber": "string",
"status": "Unknown",
"defaultCurrency": "string",
"metadata": {
"isDeleted": true
},
"supplementalData": {
"content": {
"property1": {
"property1": null,
"property2": null
},
"property2": {
"property1": null,
"property2": null
}
}
},
"modifiedDate": "2022-10-23T00:00:00Z",
"sourceModifiedDate": "2022-10-23T00:00:00Z"
} | -| `allow_sync_on_push_complete` | *Optional[bool]* | :heavy_minus_sign: | Allow a sync upon push completion. | | -| `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 | -| `timeout_in_minutes` | *Optional[int]* | :heavy_minus_sign: | Time limit for the push operation to complete before it is timed out. | | \ No newline at end of file +# CreateSupplierRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------------------------------------------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------- | +| `allow_sync_on_push_complete` | *Optional[bool]* | :heavy_minus_sign: | Allow a sync upon push completion. | | +| `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` | [Optional[shared.Supplier]](../../models/shared/supplier.md) | :heavy_minus_sign: | N/A | | +| `timeout_in_minutes` | *Optional[int]* | :heavy_minus_sign: | Time limit for the push operation to complete before it is timed out. | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/operations/createtransfertransactionrequest.md b/sync-for-expenses/docs/models/operations/createtransfertransactionrequest.md index cd1574e99..6832daf5f 100644 --- a/sync-for-expenses/docs/models/operations/createtransfertransactionrequest.md +++ b/sync-for-expenses/docs/models/operations/createtransfertransactionrequest.md @@ -1,10 +1,10 @@ -# CreateTransferTransactionRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | -| `transfer_transaction_request` | [Optional[shared.TransferTransactionRequest]](../../models/shared/transfertransactionrequest.md) | :heavy_minus_sign: | N/A | | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `transaction_id` | *str* | :heavy_check_mark: | The unique identifier for your SMB's transaction. | 336694d8-2dca-4cb5-a28d-3ccb83e55eee | \ No newline at end of file +# CreateTransferTransactionRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `transaction_id` | *str* | :heavy_check_mark: | The unique identifier for your SMB's transaction. | 336694d8-2dca-4cb5-a28d-3ccb83e55eee | +| `transfer_transaction_request` | [Optional[shared.TransferTransactionRequest]](../../models/shared/transfertransactionrequest.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/operations/deletecompanyrequest.md b/sync-for-expenses/docs/models/operations/deletecompanyrequest.md index 338ee40e5..6f16204ca 100644 --- a/sync-for-expenses/docs/models/operations/deletecompanyrequest.md +++ b/sync-for-expenses/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-expenses/docs/models/operations/deleteconnectionrequest.md b/sync-for-expenses/docs/models/operations/deleteconnectionrequest.md index 9650dc387..f4b0d4cb4 100644 --- a/sync-for-expenses/docs/models/operations/deleteconnectionrequest.md +++ b/sync-for-expenses/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-expenses/docs/models/operations/getcompanyconfigurationrequest.md b/sync-for-expenses/docs/models/operations/getcompanyconfigurationrequest.md index a5b1fe784..1ffb7ce8d 100644 --- a/sync-for-expenses/docs/models/operations/getcompanyconfigurationrequest.md +++ b/sync-for-expenses/docs/models/operations/getcompanyconfigurationrequest.md @@ -1,8 +1,8 @@ -# GetCompanyConfigurationRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +# GetCompanyConfigurationRequest + + +## 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-expenses/docs/models/operations/getcompanyinforequest.md b/sync-for-expenses/docs/models/operations/getcompanyinforequest.md index bd218de01..4e1079f7b 100644 --- a/sync-for-expenses/docs/models/operations/getcompanyinforequest.md +++ b/sync-for-expenses/docs/models/operations/getcompanyinforequest.md @@ -1,8 +1,8 @@ -# GetCompanyInfoRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +# GetCompanyInfoRequest + + +## 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-expenses/docs/models/operations/getcompanyrequest.md b/sync-for-expenses/docs/models/operations/getcompanyrequest.md index 240b811b6..295378c0b 100644 --- a/sync-for-expenses/docs/models/operations/getcompanyrequest.md +++ b/sync-for-expenses/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-expenses/docs/models/operations/getconnectionrequest.md b/sync-for-expenses/docs/models/operations/getconnectionrequest.md index 6e9f3d18b..61c906783 100644 --- a/sync-for-expenses/docs/models/operations/getconnectionrequest.md +++ b/sync-for-expenses/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-expenses/docs/models/operations/getcreatebankaccountsmodelrequest.md b/sync-for-expenses/docs/models/operations/getcreatebankaccountsmodelrequest.md index a45e1bb79..ad90536da 100644 --- a/sync-for-expenses/docs/models/operations/getcreatebankaccountsmodelrequest.md +++ b/sync-for-expenses/docs/models/operations/getcreatebankaccountsmodelrequest.md @@ -1,9 +1,9 @@ -# GetCreateBankAccountsModelRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +# GetCreateBankAccountsModelRequest + + +## 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-expenses/docs/models/operations/getcreatechartofaccountsmodelrequest.md b/sync-for-expenses/docs/models/operations/getcreatechartofaccountsmodelrequest.md index 11af40316..132aa3d9f 100644 --- a/sync-for-expenses/docs/models/operations/getcreatechartofaccountsmodelrequest.md +++ b/sync-for-expenses/docs/models/operations/getcreatechartofaccountsmodelrequest.md @@ -1,9 +1,9 @@ -# GetCreateChartOfAccountsModelRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +# GetCreateChartOfAccountsModelRequest + + +## 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-expenses/docs/models/operations/getcustomerrequest.md b/sync-for-expenses/docs/models/operations/getcustomerrequest.md index 7f0aa4a75..85e4d0a61 100644 --- a/sync-for-expenses/docs/models/operations/getcustomerrequest.md +++ b/sync-for-expenses/docs/models/operations/getcustomerrequest.md @@ -1,9 +1,9 @@ -# GetCustomerRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +# GetCustomerRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | | `customer_id` | *str* | :heavy_check_mark: | Unique identifier for a customer. | **Example 1:** 13d946f0-c5d5-42bc-b092-97ece17923ab
**Example 2:** 9wg4lep4ush5cxs79pl8sozmsndbaukll3ind4g7buqbm1h2
**Example 3:** 7110701885
**Example 4:** EILBDVJVNUAGVKRQ | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/operations/getdatastatusdatastatuses.md b/sync-for-expenses/docs/models/operations/getdatastatusdatastatuses.md index f3e954e3c..7e93388de 100644 --- a/sync-for-expenses/docs/models/operations/getdatastatusdatastatuses.md +++ b/sync-for-expenses/docs/models/operations/getdatastatusdatastatuses.md @@ -1,52 +1,7 @@ -# GetDataStatusDataStatuses - -OK - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `account_transactions` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `balance_sheet` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `bank_accounts` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `bank_transactions` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `banking_account_balances` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `banking_accounts` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `banking_transaction_categories` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `banking_transactions` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `bill_credit_notes` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `bill_payments` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `bills` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `cash_flow_statement` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `chart_of_accounts` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `commerce_company_info` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `commerce_customers` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `commerce_disputes` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `commerce_locations` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `commerce_orders` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `commerce_payment_methods` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `commerce_payments` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `commerce_product_categories` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `commerce_products` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `commerce_tax_components` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `commerce_transactions` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `company` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `credit_notes` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `customers` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `direct_costs` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `direct_incomes` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `invoices` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `item_receipts` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `items` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `journal_entries` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `journals` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `payment_methods` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `payments` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `profit_and_loss` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `purchase_orders` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `sales_orders` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `suppliers` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `tax_rates` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `tracking_categories` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | -| `transfers` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | Describes the state of data in the Codat cache for a company and data type | {
"dataType": "string",
"lastSuccessfulSync": "2022-01-01T13:00:00.000Z",
"currentStatus": "string",
"latestSyncId": "ad474a37-2003-478e-baee-9af9f1ec2fe3",
"latestSuccessfulSyncId": "8220fc90-55b6-47bc-9417-48ac6ea93101"
} | \ No newline at end of file +# GetDataStatusDataStatuses + + +## Fields + +| Field | Type | Required | Description | +| ----------- | ----------- | ----------- | ----------- | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/operations/getdatastatusrequest.md b/sync-for-expenses/docs/models/operations/getdatastatusrequest.md index 12c2e50b6..1dac483db 100644 --- a/sync-for-expenses/docs/models/operations/getdatastatusrequest.md +++ b/sync-for-expenses/docs/models/operations/getdatastatusrequest.md @@ -1,8 +1,8 @@ -# GetDataStatusRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +# GetDataStatusRequest + + +## 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-expenses/docs/models/operations/getlastsuccessfulsyncrequest.md b/sync-for-expenses/docs/models/operations/getlastsuccessfulsyncrequest.md index 9963e44ed..aa6fcd4ff 100644 --- a/sync-for-expenses/docs/models/operations/getlastsuccessfulsyncrequest.md +++ b/sync-for-expenses/docs/models/operations/getlastsuccessfulsyncrequest.md @@ -1,8 +1,8 @@ -# GetLastSuccessfulSyncRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +# GetLastSuccessfulSyncRequest + + +## 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-expenses/docs/models/operations/getlatestsyncrequest.md b/sync-for-expenses/docs/models/operations/getlatestsyncrequest.md index a3bf4745a..2943afe85 100644 --- a/sync-for-expenses/docs/models/operations/getlatestsyncrequest.md +++ b/sync-for-expenses/docs/models/operations/getlatestsyncrequest.md @@ -1,8 +1,8 @@ -# GetLatestSyncRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +# GetLatestSyncRequest + + +## 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-expenses/docs/models/operations/getmappingoptionsrequest.md b/sync-for-expenses/docs/models/operations/getmappingoptionsrequest.md index ee9e96101..c4d6c84bb 100644 --- a/sync-for-expenses/docs/models/operations/getmappingoptionsrequest.md +++ b/sync-for-expenses/docs/models/operations/getmappingoptionsrequest.md @@ -1,8 +1,8 @@ -# GetMappingOptionsRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +# GetMappingOptionsRequest + + +## 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-expenses/docs/models/operations/getpulloperationrequest.md b/sync-for-expenses/docs/models/operations/getpulloperationrequest.md index d2382bd6c..5bd36aa3e 100644 --- a/sync-for-expenses/docs/models/operations/getpulloperationrequest.md +++ b/sync-for-expenses/docs/models/operations/getpulloperationrequest.md @@ -1,9 +1,9 @@ -# GetPullOperationRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +# GetPullOperationRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | | `dataset_id` | *str* | :heavy_check_mark: | Unique identifier for the dataset that completed its sync. | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/operations/getpushoperationrequest.md b/sync-for-expenses/docs/models/operations/getpushoperationrequest.md index d667790b5..4172a7b03 100644 --- a/sync-for-expenses/docs/models/operations/getpushoperationrequest.md +++ b/sync-for-expenses/docs/models/operations/getpushoperationrequest.md @@ -1,9 +1,9 @@ -# GetPushOperationRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +# GetPushOperationRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | | `push_operation_key` | *str* | :heavy_check_mark: | Push operation key. | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/operations/getsupplierrequest.md b/sync-for-expenses/docs/models/operations/getsupplierrequest.md index b7f4e35f1..2d02010c4 100644 --- a/sync-for-expenses/docs/models/operations/getsupplierrequest.md +++ b/sync-for-expenses/docs/models/operations/getsupplierrequest.md @@ -1,9 +1,9 @@ -# GetSupplierRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +# GetSupplierRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | | `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 | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/operations/getsyncbyidrequest.md b/sync-for-expenses/docs/models/operations/getsyncbyidrequest.md index 3de850e2b..b3af01c57 100644 --- a/sync-for-expenses/docs/models/operations/getsyncbyidrequest.md +++ b/sync-for-expenses/docs/models/operations/getsyncbyidrequest.md @@ -1,9 +1,9 @@ -# GetSyncByIDRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +# GetSyncByIDRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | | `sync_id` | *str* | :heavy_check_mark: | Unique identifier for a sync. | 6fb40d5e-b13e-11ed-afa1-0242ac120002 | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/operations/getsynctransactionrequest.md b/sync-for-expenses/docs/models/operations/getsynctransactionrequest.md index d5075762f..05a2d71bf 100644 --- a/sync-for-expenses/docs/models/operations/getsynctransactionrequest.md +++ b/sync-for-expenses/docs/models/operations/getsynctransactionrequest.md @@ -1,10 +1,10 @@ -# GetSyncTransactionRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------- | ------------------------------------------------- | ------------------------------------------------- | ------------------------------------------------- | ------------------------------------------------- | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `sync_id` | *str* | :heavy_check_mark: | Unique identifier for a sync. | 6fb40d5e-b13e-11ed-afa1-0242ac120002 | +# GetSyncTransactionRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------- | ------------------------------------------------- | ------------------------------------------------- | ------------------------------------------------- | ------------------------------------------------- | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `sync_id` | *str* | :heavy_check_mark: | Unique identifier for a sync. | 6fb40d5e-b13e-11ed-afa1-0242ac120002 | | `transaction_id` | *str* | :heavy_check_mark: | The unique identifier for your SMB's transaction. | 336694d8-2dca-4cb5-a28d-3ccb83e55eee | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/operations/listcompaniesrequest.md b/sync-for-expenses/docs/models/operations/listcompaniesrequest.md index 25cc480a0..e43853f9f 100644 --- a/sync-for-expenses/docs/models/operations/listcompaniesrequest.md +++ b/sync-for-expenses/docs/models/operations/listcompaniesrequest.md @@ -1,12 +1,12 @@ -# 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 | +# 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-expenses/docs/models/operations/listconnectionsrequest.md b/sync-for-expenses/docs/models/operations/listconnectionsrequest.md index 949d3e3b6..0a3173fc6 100644 --- a/sync-for-expenses/docs/models/operations/listconnectionsrequest.md +++ b/sync-for-expenses/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 | -| `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 | +# 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-expenses/docs/models/operations/listcustomersrequest.md b/sync-for-expenses/docs/models/operations/listcustomersrequest.md index 8b6276cb4..dd4702dcc 100644 --- a/sync-for-expenses/docs/models/operations/listcustomersrequest.md +++ b/sync-for-expenses/docs/models/operations/listcustomersrequest.md @@ -1,12 +1,12 @@ -# ListCustomersRequest - - -## 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 | +# ListCustomersRequest + + +## 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-expenses/docs/models/operations/listpulloperationsrequest.md b/sync-for-expenses/docs/models/operations/listpulloperationsrequest.md index 90a05e642..af69d3d64 100644 --- a/sync-for-expenses/docs/models/operations/listpulloperationsrequest.md +++ b/sync-for-expenses/docs/models/operations/listpulloperationsrequest.md @@ -1,12 +1,12 @@ -# ListPullOperationsRequest - - -## 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 | +# ListPullOperationsRequest + + +## 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-expenses/docs/models/operations/listpushoperationsrequest.md b/sync-for-expenses/docs/models/operations/listpushoperationsrequest.md index 68a41042d..505024e30 100644 --- a/sync-for-expenses/docs/models/operations/listpushoperationsrequest.md +++ b/sync-for-expenses/docs/models/operations/listpushoperationsrequest.md @@ -1,12 +1,12 @@ -# ListPushOperationsRequest - - -## 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 | +# ListPushOperationsRequest + + +## 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-expenses/docs/models/operations/listsuppliersrequest.md b/sync-for-expenses/docs/models/operations/listsuppliersrequest.md index 0590ff1a1..f235ad517 100644 --- a/sync-for-expenses/docs/models/operations/listsuppliersrequest.md +++ b/sync-for-expenses/docs/models/operations/listsuppliersrequest.md @@ -1,12 +1,12 @@ -# ListSuppliersRequest - - -## 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 | +# ListSuppliersRequest + + +## 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-expenses/docs/models/operations/listsyncsrequest.md b/sync-for-expenses/docs/models/operations/listsyncsrequest.md index 5bf61df8e..99dd1c01c 100644 --- a/sync-for-expenses/docs/models/operations/listsyncsrequest.md +++ b/sync-for-expenses/docs/models/operations/listsyncsrequest.md @@ -1,8 +1,8 @@ -# ListSyncsRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +# ListSyncsRequest + + +## 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-expenses/docs/models/operations/listsynctransactionsrequest.md b/sync-for-expenses/docs/models/operations/listsynctransactionsrequest.md index 3293bbae1..f96943862 100644 --- a/sync-for-expenses/docs/models/operations/listsynctransactionsrequest.md +++ b/sync-for-expenses/docs/models/operations/listsynctransactionsrequest.md @@ -1,11 +1,11 @@ -# ListSyncTransactionsRequest - - -## 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 | +# ListSyncTransactionsRequest + + +## 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 | | `sync_id` | *str* | :heavy_check_mark: | Unique identifier for a sync. | 6fb40d5e-b13e-11ed-afa1-0242ac120002 | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/operations/refreshalldatatypesrequest.md b/sync-for-expenses/docs/models/operations/refreshalldatatypesrequest.md index ea381e387..18991b870 100644 --- a/sync-for-expenses/docs/models/operations/refreshalldatatypesrequest.md +++ b/sync-for-expenses/docs/models/operations/refreshalldatatypesrequest.md @@ -1,8 +1,8 @@ -# RefreshAllDataTypesRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +# RefreshAllDataTypesRequest + + +## 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-expenses/docs/models/operations/refreshdatatyperequest.md b/sync-for-expenses/docs/models/operations/refreshdatatyperequest.md index 1047c2228..fa5ebc1b8 100644 --- a/sync-for-expenses/docs/models/operations/refreshdatatyperequest.md +++ b/sync-for-expenses/docs/models/operations/refreshdatatyperequest.md @@ -1,10 +1,10 @@ -# RefreshDataTypeRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `connection_id` | *Optional[str]* | :heavy_minus_sign: | Optionally, provide a data connection id to only queue pull operations on that connection. | | +# RefreshDataTypeRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `connection_id` | *Optional[str]* | :heavy_minus_sign: | Optionally, provide a data connection id to only queue pull operations on that connection. | | | `data_type` | [shared.SchemaDataType](../../models/shared/schemadatatype.md) | :heavy_check_mark: | The key of a Codat data type | invoices | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/operations/replacecompanyrequest.md b/sync-for-expenses/docs/models/operations/replacecompanyrequest.md index cde3d20e3..2b90faf30 100644 --- a/sync-for-expenses/docs/models/operations/replacecompanyrequest.md +++ b/sync-for-expenses/docs/models/operations/replacecompanyrequest.md @@ -1,9 +1,9 @@ -# ReplaceCompanyRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -| `company_request_body` | [Optional[shared.CompanyRequestBody]](../../models/shared/companyrequestbody.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 +# 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-expenses/docs/models/operations/setcompanyconfigurationrequest.md b/sync-for-expenses/docs/models/operations/setcompanyconfigurationrequest.md index 1afe2e73f..d04be75bf 100644 --- a/sync-for-expenses/docs/models/operations/setcompanyconfigurationrequest.md +++ b/sync-for-expenses/docs/models/operations/setcompanyconfigurationrequest.md @@ -1,9 +1,9 @@ -# SetCompanyConfigurationRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | -| `company_configuration` | [Optional[shared.CompanyConfiguration]](../../models/shared/companyconfiguration.md) | :heavy_minus_sign: | N/A | | +# SetCompanyConfigurationRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | +| `company_configuration` | [Optional[shared.CompanyConfiguration]](../../models/shared/companyconfiguration.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-expenses/docs/models/operations/unlinkconnectionrequest.md b/sync-for-expenses/docs/models/operations/unlinkconnectionrequest.md index 37c72c7bc..66136f30f 100644 --- a/sync-for-expenses/docs/models/operations/unlinkconnectionrequest.md +++ b/sync-for-expenses/docs/models/operations/unlinkconnectionrequest.md @@ -1,10 +1,10 @@ -# UnlinkConnectionRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -| `request_body` | [Optional[operations.UnlinkConnectionUpdateConnection]](../../models/operations/unlinkconnectionupdateconnection.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 +# 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-expenses/docs/models/operations/unlinkconnectionupdateconnection.md b/sync-for-expenses/docs/models/operations/unlinkconnectionupdateconnection.md index 5a5f2911b..476521561 100644 --- a/sync-for-expenses/docs/models/operations/unlinkconnectionupdateconnection.md +++ b/sync-for-expenses/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-expenses/docs/models/operations/updatecompanyrequest.md b/sync-for-expenses/docs/models/operations/updatecompanyrequest.md index 47802c383..9718e2ff6 100644 --- a/sync-for-expenses/docs/models/operations/updatecompanyrequest.md +++ b/sync-for-expenses/docs/models/operations/updatecompanyrequest.md @@ -1,9 +1,9 @@ -# UpdateCompanyRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | -| `company_update_request` | [Optional[shared.CompanyUpdateRequest]](../../models/shared/companyupdaterequest.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 +# 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-expenses/docs/models/operations/updatecustomerrequest.md b/sync-for-expenses/docs/models/operations/updatecustomerrequest.md index ecdd8a1aa..75fca526e 100644 --- a/sync-for-expenses/docs/models/operations/updatecustomerrequest.md +++ b/sync-for-expenses/docs/models/operations/updatecustomerrequest.md @@ -1,14 +1,14 @@ -# UpdateCustomerRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `customer` | [OptionalNullable[shared.Customer]](../../models/shared/customer.md) | :heavy_minus_sign: | N/A | | -| `allow_sync_on_push_complete` | *Optional[bool]* | :heavy_minus_sign: | Allow a sync upon push completion. | | -| `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 | -| `customer_id` | *str* | :heavy_check_mark: | Unique identifier for a customer. | **Example 1:** 13d946f0-c5d5-42bc-b092-97ece17923ab
**Example 2:** 9wg4lep4ush5cxs79pl8sozmsndbaukll3ind4g7buqbm1h2
**Example 3:** 7110701885
**Example 4:** EILBDVJVNUAGVKRQ | -| `force_update` | *Optional[bool]* | :heavy_minus_sign: | When updating data in the destination platform Codat checks the `sourceModifiedDate` against the `lastupdated` date from the accounting software, if they're different Codat will return an error suggesting you should initiate another pull of the data. If this is set to `true` then the update will override this check. | | +# UpdateCustomerRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `allow_sync_on_push_complete` | *Optional[bool]* | :heavy_minus_sign: | Allow a sync upon push completion. | | +| `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 | +| `customer` | [Optional[shared.Customer]](../../models/shared/customer.md) | :heavy_minus_sign: | N/A | | +| `customer_id` | *str* | :heavy_check_mark: | Unique identifier for a customer. | **Example 1:** 13d946f0-c5d5-42bc-b092-97ece17923ab
**Example 2:** 9wg4lep4ush5cxs79pl8sozmsndbaukll3ind4g7buqbm1h2
**Example 3:** 7110701885
**Example 4:** EILBDVJVNUAGVKRQ | +| `force_update` | *Optional[bool]* | :heavy_minus_sign: | When updating data in the destination platform Codat checks the `sourceModifiedDate` against the `lastupdated` date from the accounting software, if they're different Codat will return an error suggesting you should initiate another pull of the data. If this is set to `true` then the update will override this check. | | | `timeout_in_minutes` | *Optional[int]* | :heavy_minus_sign: | Time limit for the push operation to complete before it is timed out. | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/operations/updateexpensetransactionrequest.md b/sync-for-expenses/docs/models/operations/updateexpensetransactionrequest.md index 44a52487c..6d6bf1e5c 100644 --- a/sync-for-expenses/docs/models/operations/updateexpensetransactionrequest.md +++ b/sync-for-expenses/docs/models/operations/updateexpensetransactionrequest.md @@ -1,10 +1,10 @@ -# UpdateExpenseTransactionRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | -| `update_expense_request` | [Optional[shared.UpdateExpenseRequest]](../../models/shared/updateexpenserequest.md) | :heavy_minus_sign: | N/A | | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `transaction_id` | *str* | :heavy_check_mark: | The unique identifier for your SMB's transaction. | 336694d8-2dca-4cb5-a28d-3ccb83e55eee | \ No newline at end of file +# UpdateExpenseTransactionRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `transaction_id` | *str* | :heavy_check_mark: | The unique identifier for your SMB's transaction. | 336694d8-2dca-4cb5-a28d-3ccb83e55eee | +| `update_expense_request` | [Optional[shared.UpdateExpenseRequest]](../../models/shared/updateexpenserequest.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/operations/updatereimbursableexpensetransactionrequest.md b/sync-for-expenses/docs/models/operations/updatereimbursableexpensetransactionrequest.md index 8f89b3945..a6ae68a80 100644 --- a/sync-for-expenses/docs/models/operations/updatereimbursableexpensetransactionrequest.md +++ b/sync-for-expenses/docs/models/operations/updatereimbursableexpensetransactionrequest.md @@ -1,10 +1,10 @@ -# UpdateReimbursableExpenseTransactionRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ---------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | -| `update_reimbursable_expense_transaction_request` | [Optional[shared.UpdateReimbursableExpenseTransactionRequest]](../../models/shared/updatereimbursableexpensetransactionrequest.md) | :heavy_minus_sign: | N/A | | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `transaction_id` | *str* | :heavy_check_mark: | The unique identifier for your SMB's transaction. | 336694d8-2dca-4cb5-a28d-3ccb83e55eee | \ No newline at end of file +# UpdateReimbursableExpenseTransactionRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------- | ----------------------------------------------------------- | ----------------------------------------------------------- | ----------------------------------------------------------- | ----------------------------------------------------------- | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `transaction_id` | *str* | :heavy_check_mark: | The unique identifier for your SMB's transaction. | 336694d8-2dca-4cb5-a28d-3ccb83e55eee | +| `update_reimbursable_expense_transaction_request` | *Optional[UpdateReimbursableExpenseTransactionRequestBody]* | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/operations/updatesupplierrequest.md b/sync-for-expenses/docs/models/operations/updatesupplierrequest.md index c8d3266f8..102e8b494 100644 --- a/sync-for-expenses/docs/models/operations/updatesupplierrequest.md +++ b/sync-for-expenses/docs/models/operations/updatesupplierrequest.md @@ -1,14 +1,14 @@ -# UpdateSupplierRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `supplier` | [OptionalNullable[shared.Supplier]](../../models/shared/supplier.md) | :heavy_minus_sign: | N/A | {
"id": "C520FFD4-F6F6-4FC2-A6D2-5D7088B2B14F",
"supplierName": "Kelly's Industrial Supplies",
"contactName": "Kelly's Industrial Supplies",
"emailAddress": "sales@kellysupplies.com",
"phone": "07999 999999",
"addresses": [
{
"type": "Billing",
"line1": "Unit 51",
"line2": "Bakersfield Industrial Estate",
"city": "Bakersfield",
"region": "California",
"country": "USA",
"postalcode": "93308"
}
],
"registrationNumber": "string",
"taxNumber": "string",
"status": "Unknown",
"defaultCurrency": "string",
"metadata": {
"isDeleted": true
},
"supplementalData": {
"content": {
"property1": {
"property1": null,
"property2": null
},
"property2": {
"property1": null,
"property2": null
}
}
},
"modifiedDate": "2022-10-23T00:00:00Z",
"sourceModifiedDate": "2022-10-23T00:00:00Z"
} | -| `allow_sync_on_push_complete` | *Optional[bool]* | :heavy_minus_sign: | Allow a sync upon push completion. | | -| `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 | -| `force_update` | *Optional[bool]* | :heavy_minus_sign: | When updating data in the destination platform Codat checks the `sourceModifiedDate` against the `lastupdated` date from the accounting software, if they're different Codat will return an error suggesting you should initiate another pull of the data. If this is set to `true` then the update will override this check. | | -| `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 | -| `timeout_in_minutes` | *Optional[int]* | :heavy_minus_sign: | Time limit for the push operation to complete before it is timed out. | | \ No newline at end of file +# UpdateSupplierRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `allow_sync_on_push_complete` | *Optional[bool]* | :heavy_minus_sign: | Allow a sync upon push completion. | | +| `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 | +| `force_update` | *Optional[bool]* | :heavy_minus_sign: | When updating data in the destination platform Codat checks the `sourceModifiedDate` against the `lastupdated` date from the accounting software, if they're different Codat will return an error suggesting you should initiate another pull of the data. If this is set to `true` then the update will override this check. | | +| `supplier` | [Optional[shared.Supplier]](../../models/shared/supplier.md) | :heavy_minus_sign: | N/A | | +| `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 | +| `timeout_in_minutes` | *Optional[int]* | :heavy_minus_sign: | Time limit for the push operation to complete before it is timed out. | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/operations/uploadexpenseattachmentrequest.md b/sync-for-expenses/docs/models/operations/uploadexpenseattachmentrequest.md index 747fb2886..9a5e7b2ec 100644 --- a/sync-for-expenses/docs/models/operations/uploadexpenseattachmentrequest.md +++ b/sync-for-expenses/docs/models/operations/uploadexpenseattachmentrequest.md @@ -1,11 +1,11 @@ -# UploadExpenseAttachmentRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | -| `attachment_upload` | [Optional[shared.AttachmentUpload]](../../models/shared/attachmentupload.md) | :heavy_minus_sign: | N/A | | -| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | -| `sync_id` | *str* | :heavy_check_mark: | Unique identifier for a sync. | 6fb40d5e-b13e-11ed-afa1-0242ac120002 | +# UploadExpenseAttachmentRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | +| `attachment_upload` | [Optional[shared.AttachmentUpload]](../../models/shared/attachmentupload.md) | :heavy_minus_sign: | N/A | | +| `company_id` | *str* | :heavy_check_mark: | Unique identifier for a company. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `sync_id` | *str* | :heavy_check_mark: | Unique identifier for a sync. | 6fb40d5e-b13e-11ed-afa1-0242ac120002 | | `transaction_id` | *str* | :heavy_check_mark: | The unique identifier for your SMB's transaction. | 336694d8-2dca-4cb5-a28d-3ccb83e55eee | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/accountingaccount.md b/sync-for-expenses/docs/models/shared/account.md similarity index 96% rename from sync-for-expenses/docs/models/shared/accountingaccount.md rename to sync-for-expenses/docs/models/shared/account.md index ad4be6cae..053072eb0 100644 --- a/sync-for-expenses/docs/models/shared/accountingaccount.md +++ b/sync-for-expenses/docs/models/shared/account.md @@ -1,52 +1,50 @@ -# ~~AccountingAccount~~ - -> **Language tip:** Accounts are also referred to as **chart of accounts**, **nominal accounts**, and **general ledger**. - -## Overview - -Accounts are the categories a business uses to record accounting transactions. From the Accounts endpoints, you can retrieve a list of all accounts for a specified company. - -The categories for an account include: -* Asset -* Expense -* Income -* Liability -* Equity. - -The same account may have a different category based on the integration it is used in. For example, a current account (known as checking in the US) should be categorized as `Asset.Current` for Xero, and `Asset.Bank.Checking` for QuickBooks Online. - -At the same time, each integration may have its own requirements to the categories. For example, a Paypal account in Xero is of the `Asset.Bank` category and therefore requires additional properties to be provided. - -To determine the list of allowed categories for a specific integration, you can: -- Follow our [Create, update, delete data](https://docs.codat.io/using-the-api/push) guide and use the [Get create account model](https://docs.codat.io/sync-for-expenses-api#/operations/get-create-chartOfAccounts-model). -- Refer to the integration's own documentation. - -> **Accounts with no category** -> -> If an account is pulled from the chart of accounts and its nominal code does not lie within the category layout for the company's accounts, then the **type** is `Unknown`. The **fullyQualifiedCategory** and **fullyQualifiedName** fields return `null`. -> -> This approach gives a true representation of the company's accounts whilst preventing distorting financials such as a company's profit and loss and balance sheet reports. - -> :warning: **DEPRECATED**: This will be removed in a future release, please migrate away from it as soon as possible. - - -## Fields - -| Field | Type | Required | Description | Example | -| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `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 | -| `current_balance` | *OptionalNullable[Decimal]* | :heavy_minus_sign: | Current balance in the account. | 0 | -| `description` | *OptionalNullable[str]* | :heavy_minus_sign: | Description for the account. | Invoices the business has issued but has not yet collected payment on. | -| `fully_qualified_category` | *OptionalNullable[str]* | :heavy_minus_sign: | Full category of the account.

For example, `Liability.Current` or `Income.Revenue`. To determine a list of possible categories for each integration, see our examples, follow our [Create, update, delete data](https://docs.codat.io/using-the-api/push) guide, or refer to the integration's own documentation. | Asset.Current | -| `fully_qualified_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Full name of the account, for example:
- `Cash On Hand`
- `Rents Held In Trust`
- `Fixed Asset` | **Example 1:** Cash On Hand
**Example 2:** Fixed Asset | -| `id` | *Optional[str]* | :heavy_minus_sign: | Identifier for the account, unique for the company. | 1b6266d1-1e44-46c5-8eb5-a8f98e03124e | -| `is_bank_account` | *Optional[bool]* | :heavy_minus_sign: | Confirms whether the account is a bank account or not. | | -| `metadata` | [Optional[shared.CreateAccountResponseMetadata]](../../models/shared/createaccountresponsemetadata.md) | :heavy_minus_sign: | N/A | | -| `modified_date` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the account. | Accounts Receivable | -| `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 | -| `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.AccountStatus]](../../models/shared/accountstatus.md) | :heavy_minus_sign: | Status of the account | Active | -| `supplemental_data` | [Optional[shared.SupplementalData]](../../models/shared/supplementaldata.md) | :heavy_minus_sign: | Supplemental data is additional data you can include in our standard data types.

It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. | | -| `type` | [Optional[shared.AccountType]](../../models/shared/accounttype.md) | :heavy_minus_sign: | Type of account | Asset | -| `valid_datatype_links` | List[[shared.CreateAccountResponseValidDataTypeLinks](../../models/shared/createaccountresponsevaliddatatypelinks.md)] | :heavy_minus_sign: | The validDatatypeLinks can be used to determine whether an account can be correctly mapped to another object; for example, accounts with a `type` of `income` might only support being used on an Invoice and Direct Income. For more information, see [Valid Data Type Links](/sync-for-expenses-api#/schemas/ValidDataTypeLinks). | | \ No newline at end of file +# Account + +> **Language tip:** Accounts are also referred to as **chart of accounts**, **nominal accounts**, and **general ledger**. + +## Overview + +Accounts are the categories a business uses to record accounting transactions. From the Accounts endpoints, you can retrieve a list of all accounts for a specified company. + +The categories for an account include: +* Asset +* Expense +* Income +* Liability +* Equity. + +The same account may have a different category based on the integration it is used in. For example, a current account (known as checking in the US) should be categorized as `Asset.Current` for Xero, and `Asset.Bank.Checking` for QuickBooks Online. + +At the same time, each integration may have its own requirements to the categories. For example, a Paypal account in Xero is of the `Asset.Bank` category and therefore requires additional properties to be provided. + +To determine the list of allowed categories for a specific integration, you can: +- Follow our [Create, update, delete data](https://docs.codat.io/using-the-api/push) guide and use the [Get create account model](https://docs.codat.io/sync-for-expenses-api#/operations/get-create-chartOfAccounts-model). +- Refer to the integration's own documentation. + +> **Accounts with no category** +> +> If an account is pulled from the chart of accounts and its nominal code does not lie within the category layout for the company's accounts, then the **type** is `Unknown`. The **fullyQualifiedCategory** and **fullyQualifiedName** fields return `null`. +> +> This approach gives a true representation of the company's accounts whilst preventing distorting financials such as a company's profit and loss and balance sheet reports. + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `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 | +| `current_balance` | *Optional[Decimal]* | :heavy_minus_sign: | Current balance in the account. | 0 | +| `description` | *Optional[str]* | :heavy_minus_sign: | Description for the account. | Invoices the business has issued but has not yet collected payment on. | +| `fully_qualified_category` | *Optional[str]* | :heavy_minus_sign: | Full category of the account.

For example, `Liability.Current` or `Income.Revenue`. To determine a list of possible categories for each integration, see our examples, follow our [Create, update, delete data](https://docs.codat.io/using-the-api/push) guide, or refer to the integration's own documentation. | Asset.Current | +| `fully_qualified_name` | *Optional[str]* | :heavy_minus_sign: | Full name of the account, for example:
- `Cash On Hand`
- `Rents Held In Trust`
- `Fixed Asset` | **Example 1:** Cash On Hand
**Example 2:** Fixed Asset | +| `id` | *Optional[str]* | :heavy_minus_sign: | Identifier for the account, unique for the company. | 1b6266d1-1e44-46c5-8eb5-a8f98e03124e | +| `is_bank_account` | *Optional[bool]* | :heavy_minus_sign: | Confirms whether the account is a bank account or not. | | +| `metadata` | [Optional[shared.Metadata]](../../models/shared/metadata.md) | :heavy_minus_sign: | N/A | | +| `modified_date` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `name` | *Optional[str]* | :heavy_minus_sign: | Name of the account. | Accounts Receivable | +| `nominal_code` | *Optional[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 | +| `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.AccountStatus]](../../models/shared/accountstatus.md) | :heavy_minus_sign: | Status of the account | Active | +| `supplemental_data` | [Optional[shared.SupplementalData]](../../models/shared/supplementaldata.md) | :heavy_minus_sign: | Supplemental data is additional data you can include in our standard data types.

It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. | | +| `type` | [Optional[shared.AccountType]](../../models/shared/accounttype.md) | :heavy_minus_sign: | Type of account | Asset | +| `valid_datatype_links` | List[[shared.ValidDataTypeLinks](../../models/shared/validdatatypelinks.md)] | :heavy_minus_sign: | The validDatatypeLinks can be used to determine whether an account can be correctly mapped to another object; for example, accounts with a `type` of `income` might only support being used on an Invoice and Direct Income. For more information, see [Valid Data Type Links](/sync-for-expenses-api#/schemas/ValidDataTypeLinks). | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/accountingaddress.md b/sync-for-expenses/docs/models/shared/accountingaddress.md index 25c7e6e6c..b5ad61e67 100644 --- a/sync-for-expenses/docs/models/shared/accountingaddress.md +++ b/sync-for-expenses/docs/models/shared/accountingaddress.md @@ -1,14 +1,14 @@ -# AccountingAddress - - -## 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 customer 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. | -| `postal_code` | *OptionalNullable[str]* | :heavy_minus_sign: | Postal code or zip code. | -| `region` | *OptionalNullable[str]* | :heavy_minus_sign: | Region of the customer address. | +# AccountingAddress + + +## 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 customer 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. | +| `postal_code` | *OptionalNullable[str]* | :heavy_minus_sign: | Postal code or zip code. | +| `region` | *OptionalNullable[str]* | :heavy_minus_sign: | Region of the customer address. | | `type` | [shared.AccountingAddressType](../../models/shared/accountingaddresstype.md) | :heavy_check_mark: | The type of the address | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/accountingaddresstype.md b/sync-for-expenses/docs/models/shared/accountingaddresstype.md index 28e84404e..bf8f750f9 100644 --- a/sync-for-expenses/docs/models/shared/accountingaddresstype.md +++ b/sync-for-expenses/docs/models/shared/accountingaddresstype.md @@ -1,20 +1,18 @@ -# AccountingAddressType - -The type of the address - -## Example Usage - -```python -from codat_sync_for_expenses.models.shared import AccountingAddressType - -value = AccountingAddressType.UNKNOWN -``` - - -## Values - -| Name | Value | -| ---------- | ---------- | -| `UNKNOWN` | Unknown | -| `BILLING` | Billing | +# AccountingAddressType + +## Example Usage + +```python +from codat_sync_for_expenses.models.shared import AccountingAddressType + +value = AccountingAddressType.UNKNOWN +``` + + +## Values + +| Name | Value | +| ---------- | ---------- | +| `UNKNOWN` | Unknown | +| `BILLING` | Billing | | `DELIVERY` | Delivery | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/accountingcustomer.md b/sync-for-expenses/docs/models/shared/accountingcustomer.md deleted file mode 100644 index 91aac8064..000000000 --- a/sync-for-expenses/docs/models/shared/accountingcustomer.md +++ /dev/null @@ -1,31 +0,0 @@ -# ~~AccountingCustomer~~ - -## Overview - -A customer is a person or organisation that buys goods or services. From the Customers endpoints, you can retrieve a [list of all the customers of a company](https://api.codat.io/swagger/index.html#/Customers/get_companies__companyId__data_customers). - -Customers' data links to accounts receivable [invoices](https://docs.codat.io/sync-for-expenses-api#/schemas/Invoice). - - -> :warning: **DEPRECATED**: This will be removed in a future release, please migrate away from it as soon as possible. - - -## Fields - -| Field | Type | Required | Description | Example | -| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `addresses` | List[[shared.Items](../../models/shared/items.md)] | :heavy_minus_sign: | An array of Addresses. | | -| `contact_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the main contact for the identified customer. | | -| `contacts` | List[[shared.Contact](../../models/shared/contact.md)] | :heavy_minus_sign: | An array of Contacts. | | -| `customer_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the customer as recorded in the accounting system, typically the company name. | | -| `default_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 | -| `email_address` | *OptionalNullable[str]* | :heavy_minus_sign: | Email address the customer can be contacted by. | | -| `id` | *Optional[str]* | :heavy_minus_sign: | Identifier for the customer, unique to the company in the accounting software. | | -| `metadata` | [Optional[shared.Metadata]](../../models/shared/metadata.md) | :heavy_minus_sign: | N/A | | -| `modified_date` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `phone` | *OptionalNullable[str]* | :heavy_minus_sign: | Phone number the customer can be contacted by. | | -| `registration_number` | *OptionalNullable[str]* | :heavy_minus_sign: | Company number. In the UK, this is typically the Companies House company registration number. | | -| `source_modified_date` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `status` | [shared.CustomerStatus](../../models/shared/customerstatus.md) | :heavy_check_mark: | Status of customer. | | -| `supplemental_data` | [Optional[shared.SupplementalData]](../../models/shared/supplementaldata.md) | :heavy_minus_sign: | Supplemental data is additional data you can include in our standard data types.

It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. | | -| `tax_number` | *OptionalNullable[str]* | :heavy_minus_sign: | Company tax number. | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/accountingsupplier.md b/sync-for-expenses/docs/models/shared/accountingsupplier.md deleted file mode 100644 index d0ef2eeb6..000000000 --- a/sync-for-expenses/docs/models/shared/accountingsupplier.md +++ /dev/null @@ -1,27 +0,0 @@ -# ~~AccountingSupplier~~ - -## Overview - -From the **Suppliers** endpoints, you can retrieve a list of [all the suppliers for a company](https://docs.codat.io/sync-for-expenses-api#/operations/list-suppliers). Suppliers' data links to accounts payable [bills](https://docs.codat.io/sync-for-expenses-api#/schemas/Bill). - -> :warning: **DEPRECATED**: This will be removed in a future release, please migrate away from it as soon as possible. - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `addresses` | List[[shared.Items](../../models/shared/items.md)] | :heavy_minus_sign: | An array of Addresses. | | -| `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. | | -| `metadata` | [Optional[shared.Metadata]](../../models/shared/metadata.md) | :heavy_minus_sign: | N/A | | -| `modified_date` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `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 | -| `registration_number` | *OptionalNullable[str]* | :heavy_minus_sign: | Company number of the supplier. In the UK, this is typically the company registration number issued by Companies House. | | -| `source_modified_date` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `status` | [shared.SupplierStatus](../../models/shared/supplierstatus.md) | :heavy_check_mark: | Status of the supplier. | | -| `supplemental_data` | [Optional[shared.SupplementalData]](../../models/shared/supplementaldata.md) | :heavy_minus_sign: | Supplemental data is additional data you can include in our standard data types.

It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. | | -| `supplier_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the supplier as recorded in the accounting system, typically the company name. | | -| `tax_number` | *OptionalNullable[str]* | :heavy_minus_sign: | Supplier's company tax number. | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/accountmappinginfo.md b/sync-for-expenses/docs/models/shared/accountmappinginfo.md index 9f9808346..8a0a19983 100644 --- a/sync-for-expenses/docs/models/shared/accountmappinginfo.md +++ b/sync-for-expenses/docs/models/shared/accountmappinginfo.md @@ -1,16 +1,17 @@ -# AccountMappingInfo - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | -| `account_type` | [Optional[shared.AccountMappingInfoAccountType]](../../models/shared/accountmappinginfoaccounttype.md) | :heavy_minus_sign: | Type of the account. | Expense | -| `currency` | *Optional[str]* | :heavy_minus_sign: | Currency of the account. | GBP | -| `fully_qualified_category` | *Optional[str]* | :heavy_minus_sign: | Full account type and category of the account | Expense.DirectCosts | -| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of account. | 127f3b99-8dc2-4b7e-854c-91ef9bd2757b | -| `is_bank_account` | *Optional[bool]* | :heavy_minus_sign: | Confirms whether the account is a bank account or not. | | -| `name` | *Optional[str]* | :heavy_minus_sign: | Name of the account as it appears in the company's accounting software. | Purchases | -| `nominal_code` | *OptionalNullable[str]* | :heavy_minus_sign: | Code used to identify each nominal account in the accounting software. | 300 | -| `valid_for` | List[[shared.ValidFor](../../models/shared/validfor.md)] | :heavy_minus_sign: | Supported endpoints for the account. | | +# AccountMappingInfo + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | +| `account_type` | [Optional[shared.AccountMappingInfoAccountType]](../../models/shared/accountmappinginfoaccounttype.md) | :heavy_minus_sign: | Type of the account. | Expense | +| `additional_properties` | Dict[str, *Any*] | :heavy_check_mark: | N/A | | +| `currency` | *Optional[str]* | :heavy_minus_sign: | Currency of the account. | GBP | +| `fully_qualified_category` | *Optional[str]* | :heavy_minus_sign: | Full account type and category of the account | Expense.DirectCosts | +| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of account. | 127f3b99-8dc2-4b7e-854c-91ef9bd2757b | +| `is_bank_account` | *Optional[bool]* | :heavy_minus_sign: | Confirms whether the account is a bank account or not. | | +| `name` | *Optional[str]* | :heavy_minus_sign: | Name of the account as it appears in the company's accounting software. | Purchases | +| `nominal_code` | *OptionalNullable[str]* | :heavy_minus_sign: | Code used to identify each nominal account in the accounting software. | 300 | +| `valid_for` | List[[shared.ValidFor](../../models/shared/validfor.md)] | :heavy_minus_sign: | Supported endpoints for the account. | | | `valid_transaction_types` | List[[shared.ValidTransactionTypes](../../models/shared/validtransactiontypes.md)] | :heavy_minus_sign: | Supported transaction types for the account. | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/accountmappinginfoaccounttype.md b/sync-for-expenses/docs/models/shared/accountmappinginfoaccounttype.md index ef9375435..a1aa5a2a0 100644 --- a/sync-for-expenses/docs/models/shared/accountmappinginfoaccounttype.md +++ b/sync-for-expenses/docs/models/shared/accountmappinginfoaccounttype.md @@ -1,22 +1,20 @@ -# AccountMappingInfoAccountType - -Type of the account. - -## Example Usage - -```python -from codat_sync_for_expenses.models.shared import AccountMappingInfoAccountType - -value = AccountMappingInfoAccountType.ASSET -``` - - -## Values - -| Name | Value | -| ----------- | ----------- | -| `ASSET` | Asset | -| `LIABILITY` | Liability | -| `INCOME` | Income | -| `EXPENSE` | Expense | +# AccountMappingInfoAccountType + +## Example Usage + +```python +from codat_sync_for_expenses.models.shared import AccountMappingInfoAccountType + +value = AccountMappingInfoAccountType.ASSET +``` + + +## Values + +| Name | Value | +| ----------- | ----------- | +| `ASSET` | Asset | +| `LIABILITY` | Liability | +| `INCOME` | Income | +| `EXPENSE` | Expense | | `EQUITY` | Equity | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/accountprototype.md b/sync-for-expenses/docs/models/shared/accountprototype.md index 69221bd5d..d520aa093 100644 --- a/sync-for-expenses/docs/models/shared/accountprototype.md +++ b/sync-for-expenses/docs/models/shared/accountprototype.md @@ -1,19 +1,19 @@ -# AccountPrototype - - -## Fields - -| Field | Type | Required | Description | Example | -| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `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 | -| `current_balance` | *OptionalNullable[Decimal]* | :heavy_minus_sign: | Current balance in the account. | 0 | -| `description` | *OptionalNullable[str]* | :heavy_minus_sign: | Description for the account. | Invoices the business has issued but has not yet collected payment on. | -| `fully_qualified_category` | *OptionalNullable[str]* | :heavy_minus_sign: | Full category of the account.

For example, `Liability.Current` or `Income.Revenue`. To determine a list of possible categories for each integration, see our examples, follow our [Create, update, delete data](https://docs.codat.io/using-the-api/push) guide, or refer to the integration's own documentation. | Asset.Current | -| `fully_qualified_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Full name of the account, for example:
- `Cash On Hand`
- `Rents Held In Trust`
- `Fixed Asset` | **Example 1:** Cash On Hand
**Example 2:** Fixed Asset | -| `is_bank_account` | *Optional[bool]* | :heavy_minus_sign: | Confirms whether the account is a bank account or not. | | -| `name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the account. | Accounts Receivable | -| `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 | -| `status` | [Optional[shared.AccountStatus]](../../models/shared/accountstatus.md) | :heavy_minus_sign: | Status of the account | Active | -| `supplemental_data` | [Optional[shared.SupplementalData]](../../models/shared/supplementaldata.md) | :heavy_minus_sign: | Supplemental data is additional data you can include in our standard data types.

It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. | | -| `type` | [Optional[shared.AccountType]](../../models/shared/accounttype.md) | :heavy_minus_sign: | Type of account | Asset | +# AccountPrototype + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `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 | +| `current_balance` | *OptionalNullable[Decimal]* | :heavy_minus_sign: | Current balance in the account. | 0 | +| `description` | *OptionalNullable[str]* | :heavy_minus_sign: | Description for the account. | Invoices the business has issued but has not yet collected payment on. | +| `fully_qualified_category` | *OptionalNullable[str]* | :heavy_minus_sign: | Full category of the account.

For example, `Liability.Current` or `Income.Revenue`. To determine a list of possible categories for each integration, see our examples, follow our [Create, update, delete data](https://docs.codat.io/using-the-api/push) guide, or refer to the integration's own documentation. | Asset.Current | +| `fully_qualified_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Full name of the account, for example:
- `Cash On Hand`
- `Rents Held In Trust`
- `Fixed Asset` | **Example 1:** Cash On Hand
**Example 2:** Fixed Asset | +| `is_bank_account` | *Optional[bool]* | :heavy_minus_sign: | Confirms whether the account is a bank account or not. | | +| `name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the account. | Accounts Receivable | +| `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 | +| `status` | [Optional[shared.AccountStatus]](../../models/shared/accountstatus.md) | :heavy_minus_sign: | Status of the account | Active | +| `supplemental_data` | [Optional[shared.SupplementalData]](../../models/shared/supplementaldata.md) | :heavy_minus_sign: | Supplemental data is additional data you can include in our standard data types.

It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. | | +| `type` | [Optional[shared.AccountType]](../../models/shared/accounttype.md) | :heavy_minus_sign: | Type of account | Asset | | `valid_datatype_links` | List[[shared.ValidDataTypeLinks](../../models/shared/validdatatypelinks.md)] | :heavy_minus_sign: | The validDatatypeLinks can be used to determine whether an account can be correctly mapped to another object; for example, accounts with a `type` of `income` might only support being used on an Invoice and Direct Income. For more information, see [Valid Data Type Links](/sync-for-expenses-api#/schemas/ValidDataTypeLinks). | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/accountreference.md b/sync-for-expenses/docs/models/shared/accountreference.md index 227c43444..afc9f6fa6 100644 --- a/sync-for-expenses/docs/models/shared/accountreference.md +++ b/sync-for-expenses/docs/models/shared/accountreference.md @@ -1,10 +1,10 @@ -# AccountReference - -Reference of the account you are transferring money from. - - -## Fields - -| Field | Type | Required | Description | -| --------------------------------- | --------------------------------- | --------------------------------- | --------------------------------- | +# AccountReference + +Data types that reference an account, for example bill and invoice line items, use an accountRef that includes the ID and name of the linked account. + + +## Fields + +| Field | Type | Required | Description | +| --------------------------------- | --------------------------------- | --------------------------------- | --------------------------------- | | `id` | *str* | :heavy_check_mark: | 'id' from the Accounts data type. | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/transfertransactionrequestaccountreference.md b/sync-for-expenses/docs/models/shared/accountreference1.md similarity index 81% rename from sync-for-expenses/docs/models/shared/transfertransactionrequestaccountreference.md rename to sync-for-expenses/docs/models/shared/accountreference1.md index b691ef214..be1e834c6 100644 --- a/sync-for-expenses/docs/models/shared/transfertransactionrequestaccountreference.md +++ b/sync-for-expenses/docs/models/shared/accountreference1.md @@ -1,10 +1,8 @@ -# TransferTransactionRequestAccountReference - -Reference of the account you are transferring money to. - - -## Fields - -| Field | Type | Required | Description | -| --------------------------------- | --------------------------------- | --------------------------------- | --------------------------------- | +# AccountReference1 + + +## Fields + +| Field | Type | Required | Description | +| --------------------------------- | --------------------------------- | --------------------------------- | --------------------------------- | | `id` | *str* | :heavy_check_mark: | 'id' from the Accounts data type. | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/accountstatus.md b/sync-for-expenses/docs/models/shared/accountstatus.md index 829cd124d..d26c60c32 100644 --- a/sync-for-expenses/docs/models/shared/accountstatus.md +++ b/sync-for-expenses/docs/models/shared/accountstatus.md @@ -1,21 +1,21 @@ -# AccountStatus - -Status of the account - -## Example Usage - -```python -from codat_sync_for_expenses.models.shared import AccountStatus - -value = AccountStatus.UNKNOWN -``` - - -## Values - -| Name | Value | -| ---------- | ---------- | -| `UNKNOWN` | Unknown | -| `ACTIVE` | Active | -| `ARCHIVED` | Archived | +# AccountStatus + +Status of the account + +## Example Usage + +```python +from codat_sync_for_expenses.models.shared import AccountStatus + +value = AccountStatus.UNKNOWN +``` + + +## Values + +| Name | Value | +| ---------- | ---------- | +| `UNKNOWN` | Unknown | +| `ACTIVE` | Active | +| `ARCHIVED` | Archived | | `PENDING` | Pending | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/accounttype.md b/sync-for-expenses/docs/models/shared/accounttype.md index 9885b254f..83650ace1 100644 --- a/sync-for-expenses/docs/models/shared/accounttype.md +++ b/sync-for-expenses/docs/models/shared/accounttype.md @@ -1,23 +1,23 @@ -# AccountType - -Type of account - -## Example Usage - -```python -from codat_sync_for_expenses.models.shared import AccountType - -value = AccountType.UNKNOWN -``` - - -## Values - -| Name | Value | -| ----------- | ----------- | -| `UNKNOWN` | Unknown | -| `ASSET` | Asset | -| `EXPENSE` | Expense | -| `INCOME` | Income | -| `LIABILITY` | Liability | +# AccountType + +Type of account + +## Example Usage + +```python +from codat_sync_for_expenses.models.shared import AccountType + +value = AccountType.UNKNOWN +``` + + +## Values + +| Name | Value | +| ----------- | ----------- | +| `UNKNOWN` | Unknown | +| `ASSET` | Asset | +| `EXPENSE` | Expense | +| `INCOME` | Income | +| `LIABILITY` | Liability | | `EQUITY` | Equity | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/adjustmenttransactionline.md b/sync-for-expenses/docs/models/shared/adjustmenttransactionline.md index 74acaa0f6..d0f87ba30 100644 --- a/sync-for-expenses/docs/models/shared/adjustmenttransactionline.md +++ b/sync-for-expenses/docs/models/shared/adjustmenttransactionline.md @@ -1,12 +1,12 @@ -# AdjustmentTransactionLine - - -## Fields - -| Field | Type | Required | Description | Example | -| --------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `account_ref` | [shared.RecordRef](../../models/shared/recordref.md) | :heavy_check_mark: | N/A | | -| `amount` | *Decimal* | :heavy_check_mark: | Amount of the line. A positive line represents a debit; a negative line represents a credit. | 50 | -| `description` | *Optional[str]* | :heavy_minus_sign: | Any private, company notes about the transaction. | APPLE.COM/BILL - 09001077498 - Card Ending: 4590 | -| `invoice_to` | [OptionalNullable[shared.InvoiceTo]](../../models/shared/invoiceto.md) | :heavy_minus_sign: | Unique identifier for the customer billed for the transaction. The `invoiceTo` object is currently supported only for QuickBooks Online and QuickBooks Desktop. | | +# AdjustmentTransactionLine + + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `account_ref` | [shared.RecordRef](../../models/shared/recordref.md) | :heavy_check_mark: | N/A | | +| `amount` | *Decimal* | :heavy_check_mark: | Amount of the line. A positive line represents a debit; a negative line represents a credit. | 50 | +| `description` | *Optional[str]* | :heavy_minus_sign: | Any private, company notes about the transaction. | APPLE.COM/BILL - 09001077498 - Card Ending: 4590 | +| `invoice_to` | [OptionalNullable[shared.InvoiceTo]](../../models/shared/invoiceto.md) | :heavy_minus_sign: | Unique identifier for the customer billed for the transaction. The `invoiceTo` object is currently supported only for QuickBooks Online and QuickBooks Desktop. | | | `tracking_refs` | List[[shared.TrackingRefAdjustmentTransaction](../../models/shared/trackingrefadjustmenttransaction.md)] | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/adjustmenttransactionrequest.md b/sync-for-expenses/docs/models/shared/adjustmenttransactionrequest.md index ca09716bf..bb0674526 100644 --- a/sync-for-expenses/docs/models/shared/adjustmenttransactionrequest.md +++ b/sync-for-expenses/docs/models/shared/adjustmenttransactionrequest.md @@ -1,13 +1,13 @@ -# AdjustmentTransactionRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `currency` | *str* | :heavy_check_mark: | Currency the transaction was recorded in. | | -| `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: | 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` | *str* | :heavy_check_mark: | Your unique identifier for the transaction. | | -| `lines` | List[[shared.AdjustmentTransactionLine](../../models/shared/adjustmenttransactionline.md)] | :heavy_check_mark: | Array of transaction lines. | | -| `reference` | *OptionalNullable[str]* | :heavy_minus_sign: | User-friendly reference for the adjustment transaction. | | \ No newline at end of file +# AdjustmentTransactionRequest + + +## Fields + +| Field | Type | Required | Description | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `currency` | *str* | :heavy_check_mark: | Currency the transaction was recorded in. | +| `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 of the transaction. | +| `id` | *str* | :heavy_check_mark: | Your unique identifier for the transaction. | +| `lines` | List[[shared.AdjustmentTransactionLine](../../models/shared/adjustmenttransactionline.md)] | :heavy_check_mark: | Array of transaction lines. | +| `reference` | *OptionalNullable[str]* | :heavy_minus_sign: | User-friendly reference for the adjustment transaction. | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/adjustmenttransactionresponse.md b/sync-for-expenses/docs/models/shared/adjustmenttransactionresponse.md index 9f2fce3ad..dbc451f13 100644 --- a/sync-for-expenses/docs/models/shared/adjustmenttransactionresponse.md +++ b/sync-for-expenses/docs/models/shared/adjustmenttransactionresponse.md @@ -1,8 +1,8 @@ -# AdjustmentTransactionResponse - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +# AdjustmentTransactionResponse + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | | `sync_id` | *Optional[str]* | :heavy_minus_sign: | Unique id of sync created | cd937d46-8e41-43a9-9477-a79158ffd98a | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/apaccountref.md b/sync-for-expenses/docs/models/shared/apaccountref.md index bcc81692d..39b73e46f 100644 --- a/sync-for-expenses/docs/models/shared/apaccountref.md +++ b/sync-for-expenses/docs/models/shared/apaccountref.md @@ -1,8 +1,8 @@ -# ApAccountRef - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | +# ApAccountRef + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for the Accounts Payable account associated with the transaction. The `apAccountRef` object is currently supported only for QuickBooks Desktop. | 8000004C-1724173136 | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/attachment.md b/sync-for-expenses/docs/models/shared/attachment.md index 1248b8574..abc9ec2af 100644 --- a/sync-for-expenses/docs/models/shared/attachment.md +++ b/sync-for-expenses/docs/models/shared/attachment.md @@ -1,10 +1,10 @@ -# Attachment - - -## Fields - -| Field | Type | Required | Description | -| -------------------------------- | -------------------------------- | -------------------------------- | -------------------------------- | -| `company_id` | *Optional[str]* | :heavy_minus_sign: | Unique ID of company in Codat | -| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of attachment | +# Attachment + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------- | -------------------------------- | -------------------------------- | -------------------------------- | +| `company_id` | *Optional[str]* | :heavy_minus_sign: | Unique ID of company in Codat | +| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of attachment | | `transaction_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of transaction | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/attachmentupload.md b/sync-for-expenses/docs/models/shared/attachmentupload.md index 02d7ac41a..7581412bd 100644 --- a/sync-for-expenses/docs/models/shared/attachmentupload.md +++ b/sync-for-expenses/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-expenses/docs/models/shared/bankaccount.md b/sync-for-expenses/docs/models/shared/bankaccount.md index e47a40d27..c9758df2e 100644 --- a/sync-for-expenses/docs/models/shared/bankaccount.md +++ b/sync-for-expenses/docs/models/shared/bankaccount.md @@ -1,39 +1,39 @@ -# BankAccount - -> **Accessing Bank Accounts through Banking API** -> -> This datatype was originally used for accessing bank account data both in accounting integrations and open banking aggregators. -> -> To view bank account data through the Banking API, please refer to the new [Banking: Account](https://docs.codat.io/sync-for-expenses-api#/schemas/Account) data type. - -## Overview - -A list of bank accounts associated with a company and a specific data connection. - -Bank accounts data includes: -* The name and ID of the account in the accounting software. -* The currency and balance of the account. -* The sort code and account number. - - -## Fields - -| Field | Type | Required | Description | Example | -| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `account_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the bank account in the accounting software. | | -| `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.

FreeAgent integrations
For Credit accounts, only the last four digits are required. For other types, the field is optional. | | -| `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. | | -| `available_balance` | *OptionalNullable[Decimal]* | :heavy_minus_sign: | Total available balance of the bank account as reported by the underlying data source. This may take into account overdrafts or pending transactions for example. | | -| `balance` | *OptionalNullable[Decimal]* | :heavy_minus_sign: | Balance of the bank account. | | -| `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 | -| `i_ban` | *OptionalNullable[str]* | :heavy_minus_sign: | International bank account number of the account. Often used when making or receiving international payments. | | -| `id` | *Optional[str]* | :heavy_minus_sign: | Identifier for the account, unique for the company in the accounting software. | | -| `institution` | *OptionalNullable[str]* | :heavy_minus_sign: | The institution of the bank account. | | -| `metadata` | [Optional[shared.Metadata]](../../models/shared/metadata.md) | :heavy_minus_sign: | N/A | | -| `modified_date` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `nominal_code` | *OptionalNullable[str]* | :heavy_minus_sign: | Code used to identify each nominal account for a business. | | -| `overdraft_limit` | *OptionalNullable[Decimal]* | :heavy_minus_sign: | Pre-arranged overdraft limit of the account.

The value is always positive. For example, an overdraftLimit of `1000` means that the balance of the account can go down to `-1000`. | | -| `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: | 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: | Status of the bank account. | Active | +# BankAccount + +> **Accessing Bank Accounts through Banking API** +> +> This datatype was originally used for accessing bank account data both in accounting integrations and open banking aggregators. +> +> To view bank account data through the Banking API, please refer to the new [Banking: Account](https://docs.codat.io/sync-for-expenses-api#/schemas/Account) data type. + +## Overview + +A list of bank accounts associated with a company and a specific data connection. + +Bank accounts data includes: +* The name and ID of the account in the accounting software. +* The currency and balance of the account. +* The sort code and account number. + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `account_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the bank account in the accounting software. | | +| `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.

FreeAgent integrations
For Credit accounts, only the last four digits are required. For other types, the field is optional. | | +| `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. | | +| `available_balance` | *OptionalNullable[Decimal]* | :heavy_minus_sign: | Total available balance of the bank account as reported by the underlying data source. This may take into account overdrafts or pending transactions for example. | | +| `balance` | *OptionalNullable[Decimal]* | :heavy_minus_sign: | Balance of the bank account. | | +| `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 | +| `i_ban` | *OptionalNullable[str]* | :heavy_minus_sign: | International bank account number of the account. Often used when making or receiving international payments. | | +| `id` | *Optional[str]* | :heavy_minus_sign: | Identifier for the account, unique for the company in the accounting software. | | +| `institution` | *OptionalNullable[str]* | :heavy_minus_sign: | The institution of the bank account. | | +| `metadata` | [Optional[shared.Metadata]](../../models/shared/metadata.md) | :heavy_minus_sign: | N/A | | +| `modified_date` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `nominal_code` | *OptionalNullable[str]* | :heavy_minus_sign: | Code used to identify each nominal account for a business. | | +| `overdraft_limit` | *OptionalNullable[Decimal]* | :heavy_minus_sign: | Pre-arranged overdraft limit of the account.

The value is always positive. For example, an overdraftLimit of `1000` means that the balance of the account can go down to `-1000`. | | +| `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: | 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: | Status of the bank account. | Active | | `supplemental_data` | [Optional[shared.SupplementalData]](../../models/shared/supplementaldata.md) | :heavy_minus_sign: | Supplemental data is additional data you can include in our standard data types.

It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/bankaccountdetails.md b/sync-for-expenses/docs/models/shared/bankaccountdetails.md index 3501548d5..effef15bc 100644 --- a/sync-for-expenses/docs/models/shared/bankaccountdetails.md +++ b/sync-for-expenses/docs/models/shared/bankaccountdetails.md @@ -1,8 +1,8 @@ -# BankAccountDetails - - -## Fields - -| Field | Type | Required | Description | Example | -| --------------------------------------------------- | --------------------------------------------------- | --------------------------------------------------- | --------------------------------------------------- | --------------------------------------------------- | +# BankAccountDetails + + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------------------------------- | --------------------------------------------------- | --------------------------------------------------- | --------------------------------------------------- | --------------------------------------------------- | | `id` | *Optional[str]* | :heavy_minus_sign: | The id of the account from which purchases are made | 32 | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/accountingbankaccount.md b/sync-for-expenses/docs/models/shared/bankaccountprototype.md similarity index 70% rename from sync-for-expenses/docs/models/shared/accountingbankaccount.md rename to sync-for-expenses/docs/models/shared/bankaccountprototype.md index 456f38005..088da96c0 100644 --- a/sync-for-expenses/docs/models/shared/accountingbankaccount.md +++ b/sync-for-expenses/docs/models/shared/bankaccountprototype.md @@ -1,41 +1,19 @@ -# ~~AccountingBankAccount~~ - -> **Accessing Bank Accounts through Banking API** -> -> This datatype was originally used for accessing bank account data both in accounting integrations and open banking aggregators. -> -> To view bank account data through the Banking API, please refer to the new [Banking: Account](https://docs.codat.io/sync-for-expenses-api#/schemas/Account) data type. - -## Overview - -A list of bank accounts associated with a company and a specific data connection. - -Bank accounts data includes: -* The name and ID of the account in the accounting software. -* The currency and balance of the account. -* The sort code and account number. - -> :warning: **DEPRECATED**: This will be removed in a future release, please migrate away from it as soon as possible. - - -## Fields - -| Field | Type | Required | Description | Example | -| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `account_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the bank account in the accounting software. | | -| `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.

FreeAgent integrations
For Credit accounts, only the last four digits are required. For other types, the field is optional. | | -| `account_type` | [Optional[shared.CreateBankAccountResponseBankAccountType]](../../models/shared/createbankaccountresponsebankaccounttype.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. | | -| `available_balance` | *OptionalNullable[Decimal]* | :heavy_minus_sign: | Total available balance of the bank account as reported by the underlying data source. This may take into account overdrafts or pending transactions for example. | | -| `balance` | *OptionalNullable[Decimal]* | :heavy_minus_sign: | Balance of the bank account. | | -| `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 | -| `i_ban` | *OptionalNullable[str]* | :heavy_minus_sign: | International bank account number of the account. Often used when making or receiving international payments. | | -| `id` | *Optional[str]* | :heavy_minus_sign: | Identifier for the account, unique for the company in the accounting software. | | -| `institution` | *OptionalNullable[str]* | :heavy_minus_sign: | The institution of the bank account. | | -| `metadata` | [Optional[shared.Metadata]](../../models/shared/metadata.md) | :heavy_minus_sign: | N/A | | -| `modified_date` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `nominal_code` | *OptionalNullable[str]* | :heavy_minus_sign: | Code used to identify each nominal account for a business. | | -| `overdraft_limit` | *OptionalNullable[Decimal]* | :heavy_minus_sign: | Pre-arranged overdraft limit of the account.

The value is always positive. For example, an overdraftLimit of `1000` means that the balance of the account can go down to `-1000`. | | -| `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: | 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: | Status of the bank account. | Active | -| `supplemental_data` | [Optional[shared.SupplementalData]](../../models/shared/supplementaldata.md) | :heavy_minus_sign: | Supplemental data is additional data you can include in our standard data types.

It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. | | \ No newline at end of file +# BankAccountPrototype + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `account_name` | *Optional[str]* | :heavy_minus_sign: | Name of the bank account in the accounting software. | | +| `account_number` | *Optional[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.

FreeAgent integrations
For Credit accounts, only the last four digits are required. For other types, the field is optional. | | +| `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. | | +| `available_balance` | *Optional[Decimal]* | :heavy_minus_sign: | Total available balance of the bank account as reported by the underlying data source. This may take into account overdrafts or pending transactions for example. | | +| `balance` | *Optional[Decimal]* | :heavy_minus_sign: | Balance of the bank account. | | +| `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 | +| `i_ban` | *Optional[str]* | :heavy_minus_sign: | International bank account number of the account. Often used when making or receiving international payments. | | +| `institution` | *Optional[str]* | :heavy_minus_sign: | The institution of the bank account. | | +| `nominal_code` | *Optional[str]* | :heavy_minus_sign: | Code used to identify each nominal account for a business. | | +| `overdraft_limit` | *Optional[Decimal]* | :heavy_minus_sign: | Pre-arranged overdraft limit of the account.

The value is always positive. For example, an overdraftLimit of `1000` means that the balance of the account can go down to `-1000`. | | +| `sort_code` | *Optional[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. | | +| `status` | [Optional[shared.BankAccountStatus]](../../models/shared/bankaccountstatus.md) | :heavy_minus_sign: | Status of the bank account. | Active | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/bankaccountreference.md b/sync-for-expenses/docs/models/shared/bankaccountreference.md index 9e4e2473d..4cd6d1ae5 100644 --- a/sync-for-expenses/docs/models/shared/bankaccountreference.md +++ b/sync-for-expenses/docs/models/shared/bankaccountreference.md @@ -1,8 +1,10 @@ -# BankAccountReference - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | -| `id` | *Optional[str]* | :heavy_minus_sign: | Identifier of the bank account. | 787dfb37-5707-4dc0-8a86-8d74e4cc78ea | \ No newline at end of file +# BankAccountReference + +Links to the Account transactions data type. + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------- | ---------------------------------------------- | ---------------------------------------------- | ---------------------------------------------- | +| `id` | *Optional[str]* | :heavy_minus_sign: | Bank account 'id' for the account transaction. | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/bankaccountstatus.md b/sync-for-expenses/docs/models/shared/bankaccountstatus.md index b87e4763f..6d115c45d 100644 --- a/sync-for-expenses/docs/models/shared/bankaccountstatus.md +++ b/sync-for-expenses/docs/models/shared/bankaccountstatus.md @@ -1,21 +1,19 @@ -# BankAccountStatus - -Status of the bank account. - -## Example Usage - -```python -from codat_sync_for_expenses.models.shared import BankAccountStatus - -value = BankAccountStatus.UNKNOWN -``` - - -## Values - -| Name | Value | -| ---------- | ---------- | -| `UNKNOWN` | Unknown | -| `ACTIVE` | Active | -| `ARCHIVED` | Archived | +# BankAccountStatus + +## Example Usage + +```python +from codat_sync_for_expenses.models.shared import BankAccountStatus + +value = BankAccountStatus.UNKNOWN +``` + + +## Values + +| Name | Value | +| ---------- | ---------- | +| `UNKNOWN` | Unknown | +| `ACTIVE` | Active | +| `ARCHIVED` | Archived | | `PENDING` | Pending | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/bankaccounttype.md b/sync-for-expenses/docs/models/shared/bankaccounttype.md index 60adff60e..f3c9241d7 100644 --- a/sync-for-expenses/docs/models/shared/bankaccounttype.md +++ b/sync-for-expenses/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_expenses.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_expenses.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-expenses/docs/models/shared/clientratelimitwebhook.md b/sync-for-expenses/docs/models/shared/clientratelimitwebhook.md index 36e2030f0..8e226e6ce 100644 --- a/sync-for-expenses/docs/models/shared/clientratelimitwebhook.md +++ b/sync-for-expenses/docs/models/shared/clientratelimitwebhook.md @@ -1,11 +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 +# 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: | The date time in UTC the event was generated in Codat. | | +| `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-expenses/docs/models/shared/clientratelimitwebhookpayload.md b/sync-for-expenses/docs/models/shared/clientratelimitwebhookpayload.md index 41b82096c..f60f7cdf6 100644 --- a/sync-for-expenses/docs/models/shared/clientratelimitwebhookpayload.md +++ b/sync-for-expenses/docs/models/shared/clientratelimitwebhookpayload.md @@ -1,10 +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 +# ClientRateLimitWebhookPayload + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------- | +| `daily_quota` | *Optional[int]* | :heavy_minus_sign: | The number of available requests per day. | +| `expiry_date` | *Optional[str]* | :heavy_minus_sign: | The date time in UTC when your daily quota is reset. | +| `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-expenses/docs/models/shared/codatfile.md b/sync-for-expenses/docs/models/shared/codatfile.md index 07b4ca48c..3eba70262 100644 --- a/sync-for-expenses/docs/models/shared/codatfile.md +++ b/sync-for-expenses/docs/models/shared/codatfile.md @@ -1,10 +1,10 @@ -# CodatFile - - -## Fields - -| Field | Type | Required | Description | -| -------------------------------------------- | -------------------------------------------- | -------------------------------------------- | -------------------------------------------- | -| `content` | *Union[bytes, IO[bytes], io.BufferedReader]* | :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 +# 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-expenses/docs/models/shared/companies.md b/sync-for-expenses/docs/models/shared/companies.md index 670c41db2..a4a43b1c2 100644 --- a/sync-for-expenses/docs/models/shared/companies.md +++ b/sync-for-expenses/docs/models/shared/companies.md @@ -1,12 +1,12 @@ -# 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 | | +# 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-expenses/docs/models/shared/company.md b/sync-for-expenses/docs/models/shared/company.md index 1d19987ed..352f2dab7 100644 --- a/sync-for-expenses/docs/models/shared/company.md +++ b/sync-for-expenses/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-expenses-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: | 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. | | -| `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 +# 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-expenses-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: | Date of the transfer transaction as recorded in the accounting software. | | +| `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: | Date of the transfer transaction as recorded in the accounting software. | | +| `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-expenses/docs/models/shared/companyconfiguration.md b/sync-for-expenses/docs/models/shared/companyconfiguration.md index 00c9598fb..d842fe8df 100644 --- a/sync-for-expenses/docs/models/shared/companyconfiguration.md +++ b/sync-for-expenses/docs/models/shared/companyconfiguration.md @@ -1,10 +1,10 @@ -# CompanyConfiguration - - -## Fields - -| Field | Type | Required | Description | -| ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | -| `bank_account` | [shared.BankAccountDetails](../../models/shared/bankaccountdetails.md) | :heavy_check_mark: | N/A | -| `customer` | [shared.CustomerDetails](../../models/shared/customerdetails.md) | :heavy_check_mark: | N/A | +# CompanyConfiguration + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | +| `bank_account` | [shared.BankAccountDetails](../../models/shared/bankaccountdetails.md) | :heavy_check_mark: | N/A | +| `customer` | [shared.CustomerDetails](../../models/shared/customerdetails.md) | :heavy_check_mark: | N/A | | `supplier` | [shared.SupplierDetails](../../models/shared/supplierdetails.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/companydetails.md b/sync-for-expenses/docs/models/shared/companydetails.md new file mode 100644 index 000000000..21a5e9c81 --- /dev/null +++ b/sync-for-expenses/docs/models/shared/companydetails.md @@ -0,0 +1,18 @@ +# CompanyDetails + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `created` | *Optional[str]* | :heavy_minus_sign: | Date of the transfer transaction as recorded in the accounting software. | | +| `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: | Date of the transfer transaction as recorded in the accounting software. | | +| `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-expenses/docs/models/shared/companyinformation.md b/sync-for-expenses/docs/models/shared/companyinformation.md index 0b027bf67..7586eb940 100644 --- a/sync-for-expenses/docs/models/shared/companyinformation.md +++ b/sync-for-expenses/docs/models/shared/companyinformation.md @@ -1,27 +1,27 @@ -# CompanyInformation - -Company info provides standard details about a linked company such as their address, phone number, and company registration. - -> **Company information or companies?** -> -> Company information is standard information that is held in the accounting software about a company. `Companies` is an endpoint that lists businesses in the Codat system that have linked and shared their data sources. - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `accounting_platform_ref` | *OptionalNullable[str]* | :heavy_minus_sign: | Identifier or reference for the company in the accounting software. | | -| `addresses` | List[[shared.AccountingAddress](../../models/shared/accountingaddress.md)] | :heavy_minus_sign: | An array of Addresses. | | -| `base_currency` | *OptionalNullable[str]* | :heavy_minus_sign: | Currency set in the accounting software of the linked company. Used by the currency rate. | | -| `company_legal_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Registered legal name of the linked company. | | -| `company_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the linked company. | | -| `created_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 | -| `financial_year_start_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 | -| `ledger_lock_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 | -| `phone_numbers` | List[[shared.Phone](../../models/shared/phone.md)] | :heavy_minus_sign: | An array of phone numbers. | | -| `registration_number` | *OptionalNullable[str]* | :heavy_minus_sign: | Registration number given to the linked company by the companies authority in the country of origin. In the UK this is Companies House. | | -| `source_urls` | Dict[str, *Nullable[str]*] | :heavy_minus_sign: | URL addresses for the accounting source.

For example, for Xero integrations two URLs are returned. These have many potential use cases, such as [deep linking](https://developer.xero.com/documentation/api-guides/deep-link-xero). | | -| `supplemental_data` | [Optional[shared.SupplementalData]](../../models/shared/supplementaldata.md) | :heavy_minus_sign: | Supplemental data is additional data you can include in our standard data types.

It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. | | -| `tax_number` | *OptionalNullable[str]* | :heavy_minus_sign: | Company tax number. | | -| `web_links` | List[[shared.Weblink](../../models/shared/weblink.md)] | :heavy_minus_sign: | An array of weblinks. | | \ No newline at end of file +# CompanyInformation + +Company info provides standard details about a linked company such as their address, phone number, and company registration. + +> **Company information or companies?** +> +> Company information is standard information that is held in the accounting software about a company. `Companies` is an endpoint that lists businesses in the Codat system that have linked and shared their data sources. + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `accounting_platform_ref` | *OptionalNullable[str]* | :heavy_minus_sign: | Identifier or reference for the company in the accounting software. | +| `addresses` | List[[shared.AccountingAddress](../../models/shared/accountingaddress.md)] | :heavy_minus_sign: | An array of Addresses. | +| `base_currency` | *OptionalNullable[str]* | :heavy_minus_sign: | Currency set in the accounting software of the linked company. Used by the currency rate. | +| `company_legal_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Registered legal name of the linked company. | +| `company_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the linked company. | +| `created_date` | *Optional[str]* | :heavy_minus_sign: | Date the linked company was created in the accounting software. | +| `financial_year_start_date` | *Optional[str]* | :heavy_minus_sign: | Start date of the financial year for the company. | +| `ledger_lock_date` | *Optional[str]* | :heavy_minus_sign: | If set in the accounting software, the date (in the ISO 8601 date/time format) after which accounting transactions cannot be edited. Commonly used when books are closed at year-end. | +| `phone_numbers` | List[[shared.PhoneNumberItems](../../models/shared/phonenumberitems.md)] | :heavy_minus_sign: | An array of phone numbers. | +| `registration_number` | *OptionalNullable[str]* | :heavy_minus_sign: | Registration number given to the linked company by the companies authority in the country of origin. In the UK this is Companies House. | +| `source_urls` | Dict[str, *str*] | :heavy_minus_sign: | URL addresses for the accounting source.

For example, for Xero integrations two URLs are returned. These have many potential use cases, such as [deep linking](https://developer.xero.com/documentation/api-guides/deep-link-xero). | +| `supplemental_data` | [Optional[shared.SupplementalData]](../../models/shared/supplementaldata.md) | :heavy_minus_sign: | Supplemental data is additional data you can include in our standard data types.

It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. | +| `tax_number` | *OptionalNullable[str]* | :heavy_minus_sign: | Company tax number. | +| `web_links` | List[[shared.Weblink](../../models/shared/weblink.md)] | :heavy_minus_sign: | An array of weblinks. | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/companyinformationschemastype.md b/sync-for-expenses/docs/models/shared/companyinformationschemastype.md index 89193e999..bbd76b474 100644 --- a/sync-for-expenses/docs/models/shared/companyinformationschemastype.md +++ b/sync-for-expenses/docs/models/shared/companyinformationschemastype.md @@ -1,20 +1,20 @@ -# CompanyInformationSchemasType - -The type of the weblink. - -## Example Usage - -```python -from codat_sync_for_expenses.models.shared import CompanyInformationSchemasType - -value = CompanyInformationSchemasType.WEBSITE -``` - - -## Values - -| Name | Value | -| --------- | --------- | -| `WEBSITE` | Website | -| `SOCIAL` | Social | +# CompanyInformationSchemasType + +The type of the weblink. + +## Example Usage + +```python +from codat_sync_for_expenses.models.shared import CompanyInformationSchemasType + +value = CompanyInformationSchemasType.WEBSITE +``` + + +## Values + +| Name | Value | +| --------- | --------- | +| `WEBSITE` | Website | +| `SOCIAL` | Social | | `UNKNOWN` | Unknown | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/companyinformationtype.md b/sync-for-expenses/docs/models/shared/companyinformationtype.md index 5fe0b49ca..f28548f62 100644 --- a/sync-for-expenses/docs/models/shared/companyinformationtype.md +++ b/sync-for-expenses/docs/models/shared/companyinformationtype.md @@ -1,22 +1,18 @@ -# CompanyInformationType - -The type of phone number - -## Example Usage - -```python -from codat_sync_for_expenses.models.shared import CompanyInformationType - -value = CompanyInformationType.PRIMARY -``` - - -## Values - -| Name | Value | -| ---------- | ---------- | -| `PRIMARY` | Primary | -| `LANDLINE` | Landline | -| `MOBILE` | Mobile | -| `FAX` | Fax | -| `UNKNOWN` | Unknown | \ No newline at end of file +# CompanyInformationType + +## Example Usage + +```python +from codat_sync_for_expenses.models.shared import CompanyInformationType + +value = CompanyInformationType.WEBSITE +``` + + +## Values + +| Name | Value | +| --------- | --------- | +| `WEBSITE` | Website | +| `SOCIAL` | Social | +| `UNKNOWN` | Unknown | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/companyreference.md b/sync-for-expenses/docs/models/shared/companyreference.md index b651f69d5..97b15c6bc 100644 --- a/sync-for-expenses/docs/models/shared/companyreference.md +++ b/sync-for-expenses/docs/models/shared/companyreference.md @@ -1,12 +1,12 @@ -# 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. | +# 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-expenses/docs/models/shared/companyreferencelinks.md b/sync-for-expenses/docs/models/shared/companyreferencelinks.md index ee01fd320..a4c491724 100644 --- a/sync-for-expenses/docs/models/shared/companyreferencelinks.md +++ b/sync-for-expenses/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-expenses/docs/models/shared/companyrequestbody.md b/sync-for-expenses/docs/models/shared/companyrequestbody.md index 3ae35b3c7..107790e6e 100644 --- a/sync-for-expenses/docs/models/shared/companyrequestbody.md +++ b/sync-for-expenses/docs/models/shared/companyrequestbody.md @@ -1,10 +1,10 @@ -# 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 | +# 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-expenses/docs/models/shared/companysyncstatus.md b/sync-for-expenses/docs/models/shared/companysyncstatus.md index 8c66b8b9f..49ebd2a5a 100644 --- a/sync-for-expenses/docs/models/shared/companysyncstatus.md +++ b/sync-for-expenses/docs/models/shared/companysyncstatus.md @@ -1,15 +1,16 @@ -# CompanySyncStatus - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `company_id` | *OptionalNullable[str]* | :heavy_minus_sign: | Unique identifier for your SMB in Codat. | d4d73051-ed31-42b6-99f6-d288cd940992 | -| `data_pushed` | *Optional[bool]* | :heavy_minus_sign: | Boolean of whether the sync resulted in data being pushed. | | -| `error_message` | *OptionalNullable[str]* | :heavy_minus_sign: | Error message of the sync. | | -| `sync_exception_message` | *OptionalNullable[str]* | :heavy_minus_sign: | Exception message of the sync. | | -| `sync_id` | *OptionalNullable[str]* | :heavy_minus_sign: | Unique identifier of the sync. | a6a22aff-a43a-411d-a910-2dae73217cce | -| `sync_status` | *OptionalNullable[str]* | :heavy_minus_sign: | Text status of the sync. | **Example 1:** Complete
**Example 2:** PushError
**Example 3:** Started
**Example 4:** NotStarted
**Example 5:** Pushing | -| `sync_status_code` | *Optional[int]* | :heavy_minus_sign: | Status code of the sync. | 2000 | -| `sync_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 +# CompanySyncStatus + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | +| `additional_properties` | Dict[str, *Any*] | :heavy_check_mark: | N/A | | +| `company_id` | *OptionalNullable[str]* | :heavy_minus_sign: | Unique identifier for your SMB in Codat. | d4d73051-ed31-42b6-99f6-d288cd940992 | +| `data_pushed` | *Optional[bool]* | :heavy_minus_sign: | Boolean of whether the sync resulted in data being pushed. | | +| `error_message` | *OptionalNullable[str]* | :heavy_minus_sign: | Error message of the sync. | | +| `sync_exception_message` | *OptionalNullable[str]* | :heavy_minus_sign: | Exception message of the sync. | | +| `sync_id` | *OptionalNullable[str]* | :heavy_minus_sign: | Unique identifier of the sync. | a6a22aff-a43a-411d-a910-2dae73217cce | +| `sync_status` | *OptionalNullable[str]* | :heavy_minus_sign: | Text status of the sync. | **Example 1:** Complete
**Example 2:** PushError
**Example 3:** Started
**Example 4:** NotStarted
**Example 5:** Pushing | +| `sync_status_code` | *Optional[int]* | :heavy_minus_sign: | Status code of the sync. | 2000 | +| `sync_utc` | *Optional[str]* | :heavy_minus_sign: | Datetime of the sync. | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/companyupdaterequest.md b/sync-for-expenses/docs/models/shared/companyupdaterequest.md index c79edb11b..1ae031209 100644 --- a/sync-for-expenses/docs/models/shared/companyupdaterequest.md +++ b/sync-for-expenses/docs/models/shared/companyupdaterequest.md @@ -1,10 +1,10 @@ -# 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 | +# 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-expenses/docs/models/shared/connection.md b/sync-for-expenses/docs/models/shared/connection.md index 515e43211..568133a11 100644 --- a/sync-for-expenses/docs/models/shared/connection.md +++ b/sync-for-expenses/docs/models/shared/connection.md @@ -1,30 +1,31 @@ -# Connection - -A connection represents a [company's](https://docs.codat.io/sync-for-expenses-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 | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `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 +# Connection + +A connection represents a [company's](https://docs.codat.io/sync-for-expenses-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: | Date of the transfer transaction as recorded in the accounting software. | | +| `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: | Date of the transfer transaction as recorded in the accounting software. | | +| `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-expenses/docs/models/shared/connections.md b/sync-for-expenses/docs/models/shared/connections.md index 69b3bdc2c..29a1b8ed3 100644 --- a/sync-for-expenses/docs/models/shared/connections.md +++ b/sync-for-expenses/docs/models/shared/connections.md @@ -1,12 +1,12 @@ -# 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 | | +# 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-expenses/docs/models/shared/contact.md b/sync-for-expenses/docs/models/shared/contact.md index 2be9860ce..16ae82a81 100644 --- a/sync-for-expenses/docs/models/shared/contact.md +++ b/sync-for-expenses/docs/models/shared/contact.md @@ -1,13 +1,13 @@ -# Contact - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `address` | [Optional[shared.Items]](../../models/shared/items.md) | :heavy_minus_sign: | N/A | | -| `email` | *OptionalNullable[str]* | :heavy_minus_sign: | Email of a contact for a customer. | | -| `modified_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 | -| `name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of a contact for a customer. | | -| `phone` | List[[shared.PhoneNumberItems](../../models/shared/phonenumberitems.md)] | :heavy_minus_sign: | An array of Phone numbers. | | -| `status` | [shared.CustomerStatus](../../models/shared/customerstatus.md) | :heavy_check_mark: | Status of customer. | | \ No newline at end of file +# Contact + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | +| `address` | [Optional[shared.Items]](../../models/shared/items.md) | :heavy_minus_sign: | An object of Address information. | +| `email` | *OptionalNullable[str]* | :heavy_minus_sign: | Email of a contact for a customer. | +| `modified_date` | *Optional[str]* | :heavy_minus_sign: | Date of the transfer transaction as recorded in the accounting software. | +| `name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of a contact for a customer. | +| `phone` | List[[shared.PhoneNumberItems](../../models/shared/phonenumberitems.md)] | :heavy_minus_sign: | An array of Phone numbers. | +| `status` | [shared.CustomerStatus](../../models/shared/customerstatus.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/createaccountresponse.md b/sync-for-expenses/docs/models/shared/createaccountresponse.md index a910294dc..894a83723 100644 --- a/sync-for-expenses/docs/models/shared/createaccountresponse.md +++ b/sync-for-expenses/docs/models/shared/createaccountresponse.md @@ -1,21 +1,21 @@ -# CreateAccountResponse - - -## 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` | [OptionalNullable[shared.AccountingAccount]](../../models/shared/accountingaccount.md) | :heavy_minus_sign: | N/A | | -| `data_connection_key` | *str* | :heavy_check_mark: | Unique identifier for a company's data connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | -| `data_type` | [Optional[shared.DataType]](../../models/shared/datatype.md) | :heavy_minus_sign: | Available data types | invoices | -| `error_message` | *OptionalNullable[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` | *OptionalNullable[int]* | :heavy_minus_sign: | Number of minutes the push operation must complete within before it times out. | | -| ~~`timeout_in_seconds`~~ | *OptionalNullable[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 +# CreateAccountResponse + + +## 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: | The datetime when the push was completed, null if Pending. | | +| `data` | [OptionalNullable[shared.CreateAccountResponseAllOfData]](../../models/shared/createaccountresponseallofdata.md) | :heavy_minus_sign: | N/A | | +| `data_connection_key` | *str* | :heavy_check_mark: | Unique identifier for a company's data connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | +| `data_type` | [Optional[shared.DataType]](../../models/shared/datatype.md) | :heavy_minus_sign: | Available data types | invoices | +| `error_message` | *OptionalNullable[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: | The datetime when the push was requested. | | +| `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` | *OptionalNullable[int]* | :heavy_minus_sign: | Number of minutes the push operation must complete within before it times out. | | +| ~~`timeout_in_seconds`~~ | *OptionalNullable[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-expenses/docs/models/shared/createaccountresponseallofdata.md b/sync-for-expenses/docs/models/shared/createaccountresponseallofdata.md new file mode 100644 index 000000000..d009c613e --- /dev/null +++ b/sync-for-expenses/docs/models/shared/createaccountresponseallofdata.md @@ -0,0 +1,23 @@ +# CreateAccountResponseAllOfData + + +## 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. | +| `current_balance` | *Optional[Decimal]* | :heavy_minus_sign: | Current balance in the account. | +| `description` | *Optional[str]* | :heavy_minus_sign: | Description for the account. | +| `fully_qualified_category` | *Optional[str]* | :heavy_minus_sign: | Full category of the account. For example, `Liability.Current` or `Income.Revenue`. To determine a list of possible categories for each integration, see our examples, follow our [Create, update, delete data](https://docs.codat.io/using-the-api/push) guide, or refer to the integration's own documentation. | +| `fully_qualified_name` | *Optional[str]* | :heavy_minus_sign: | Full name of the account, for example: - `Cash On Hand` - `Rents Held In Trust` - `Fixed Asset` | +| `id` | *Optional[str]* | :heavy_minus_sign: | Identifier for the account, unique for the company. | +| `is_bank_account` | *Optional[bool]* | :heavy_minus_sign: | Confirms whether the account is a bank account or not. | +| `metadata` | [Optional[shared.Metadata]](../../models/shared/metadata.md) | :heavy_minus_sign: | N/A | +| `modified_date` | *Optional[str]* | :heavy_minus_sign: | The date when the record was last fetched from the accounting software, commerce software, or open banking provider and updated in Codat’s data cache. Use it to identify and retrieve records that have changed since your last fetch. For example, filtering `modifiedDate` to today will provide new records updated in Codat today. This date is populated for all data types except for attachments, balance sheets, company information, and profit & loss reports ([read more](https://docs.codat.io/using-the-api/modified-dates#modified-date)). In Codat's data model, dates and times are represented using the ISO 8601 standard. | +| `name` | *Optional[str]* | :heavy_minus_sign: | Name of the account. | +| `nominal_code` | *Optional[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 | +| `supplemental_data` | [Optional[shared.SupplementalData]](../../models/shared/supplementaldata.md) | :heavy_minus_sign: | N/A | +| `type` | [Optional[shared.AccountType]](../../models/shared/accounttype.md) | :heavy_minus_sign: | N/A | +| `valid_datatype_links` | List[[shared.ValidDataTypeLinks](../../models/shared/validdatatypelinks.md)] | :heavy_minus_sign: | The validDatatypeLinks can be used to determine whether an account can be correctly mapped to another object; for example, accounts with a `type` of `income` might only support being used on an Invoice and Direct Income. For more information, see [Valid Data Type Links](/sync-for-expenses-api#/schemas/ValidDataTypeLinks). | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/createaccountresponsemetadata.md b/sync-for-expenses/docs/models/shared/createaccountresponsemetadata.md deleted file mode 100644 index 33f612f3f..000000000 --- a/sync-for-expenses/docs/models/shared/createaccountresponsemetadata.md +++ /dev/null @@ -1,8 +0,0 @@ -# CreateAccountResponseMetadata - - -## Fields - -| Field | Type | Required | Description | -| ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | -| `is_deleted` | *OptionalNullable[bool]* | :heavy_minus_sign: | Indicates whether the record has been deleted in the third-party system this record originated from. | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/createaccountresponsevaliddatatypelinks.md b/sync-for-expenses/docs/models/shared/createaccountresponsevaliddatatypelinks.md deleted file mode 100644 index 00f6b195f..000000000 --- a/sync-for-expenses/docs/models/shared/createaccountresponsevaliddatatypelinks.md +++ /dev/null @@ -1,50 +0,0 @@ -# CreateAccountResponseValidDataTypeLinks - -When querying Codat's data model, some data types return `validDatatypeLinks` metadata in the JSON response. This indicates where that object can be used as a reference—a _valid link_—when creating or updating other data. - -For example, `validDatatypeLinks` might indicate the following references: - -- Which tax rates are valid to use on the line item of a bill. -- Which items can be used when creating an invoice. - -You can use `validDatatypeLinks` to present your SMB customers with only valid choices when selecting objects from a list, for example. - -## `validDatatypeLinks` example - -The following example uses the `Accounting.Accounts` data type. It shows that, on the linked integration, this account is valid as the account on a payment or bill payment; and as the account referenced on the line item of a direct income or direct cost. Because there is no valid link to Invoices or Bills, using this account on those data types will result in an error. - -```json validDatatypeLinks for an account -{ - "id": "bd9e85e0-0478-433d-ae9f-0b3c4f04bfe4", - "nominalCode": "090", - "name": "Business Bank Account", - #... - "validDatatypeLinks": [ - { - "property": "Id", - "links": [ - "Payment.AccountRef.Id", - "BillPayment.AccountRef.Id", - "DirectIncome.LineItems.AccountRef.Id", - "DirectCost.LineItems.AccountRef.Id" - ] - } - ] - } -``` - - - -## Support for `validDatatypeLinks` - -Codat currently supports `validDatatypeLinks` for some data types on our Xero, QuickBooks Online, QuickBooks Desktop, Exact (NL), and Sage Business Cloud integrations. - -If you'd like us to extend support to more data types or integrations, suggest or vote for this on our Product Roadmap. - - -## Fields - -| Field | Type | Required | Description | -| ------------------------------------------------------- | ------------------------------------------------------- | ------------------------------------------------------- | ------------------------------------------------------- | -| `links` | List[*str*] | :heavy_minus_sign: | Supported `dataTypes` that the record can be linked to. | -| `property` | *OptionalNullable[str]* | :heavy_minus_sign: | The property from the account that can be linked. | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/createbankaccountresponse.md b/sync-for-expenses/docs/models/shared/createbankaccountresponse.md index 253e20888..5b5163ef0 100644 --- a/sync-for-expenses/docs/models/shared/createbankaccountresponse.md +++ b/sync-for-expenses/docs/models/shared/createbankaccountresponse.md @@ -1,21 +1,21 @@ -# CreateBankAccountResponse - - -## 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` | [OptionalNullable[shared.AccountingBankAccount]](../../models/shared/accountingbankaccount.md) | :heavy_minus_sign: | N/A | | -| `data_connection_key` | *str* | :heavy_check_mark: | Unique identifier for a company's data connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | -| `data_type` | [Optional[shared.DataType]](../../models/shared/datatype.md) | :heavy_minus_sign: | Available data types | invoices | -| `error_message` | *OptionalNullable[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` | *OptionalNullable[int]* | :heavy_minus_sign: | Number of minutes the push operation must complete within before it times out. | | -| ~~`timeout_in_seconds`~~ | *OptionalNullable[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 +# CreateBankAccountResponse + + +## 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: | The datetime when the push was completed, null if Pending. | | +| `data` | [OptionalNullable[shared.CreateBankAccountResponseAllOfData]](../../models/shared/createbankaccountresponseallofdata.md) | :heavy_minus_sign: | N/A | | +| `data_connection_key` | *str* | :heavy_check_mark: | Unique identifier for a company's data connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | +| `data_type` | [Optional[shared.DataType]](../../models/shared/datatype.md) | :heavy_minus_sign: | Available data types | invoices | +| `error_message` | *OptionalNullable[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: | The datetime when the push was requested. | | +| `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` | *OptionalNullable[int]* | :heavy_minus_sign: | Number of minutes the push operation must complete within before it times out. | | +| ~~`timeout_in_seconds`~~ | *OptionalNullable[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-expenses/docs/models/shared/createbankaccountresponseallofdata.md b/sync-for-expenses/docs/models/shared/createbankaccountresponseallofdata.md new file mode 100644 index 000000000..052c996ce --- /dev/null +++ b/sync-for-expenses/docs/models/shared/createbankaccountresponseallofdata.md @@ -0,0 +1,24 @@ +# CreateBankAccountResponseAllOfData + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `account_name` | *Optional[str]* | :heavy_minus_sign: | Name of the bank account in the accounting software. | +| `account_number` | *Optional[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. FreeAgent integrations For Credit accounts, only the last four digits are required. For other types, the field is optional. | +| `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. | +| `available_balance` | *Optional[Decimal]* | :heavy_minus_sign: | Total available balance of the bank account as reported by the underlying data source. This may take into account overdrafts or pending transactions for example. | +| `balance` | *Optional[Decimal]* | :heavy_minus_sign: | Balance of the bank account. | +| `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. | +| `i_ban` | *Optional[str]* | :heavy_minus_sign: | International bank account number of the account. Often used when making or receiving international payments. | +| `id` | *Optional[str]* | :heavy_minus_sign: | Identifier for the account, unique for the company in the accounting software. | +| `institution` | *Optional[str]* | :heavy_minus_sign: | The institution of the bank account. | +| `metadata` | [Optional[shared.Metadata]](../../models/shared/metadata.md) | :heavy_minus_sign: | N/A | +| `modified_date` | *Optional[str]* | :heavy_minus_sign: | The date when the record was last fetched from the accounting software, commerce software, or open banking provider and updated in Codat’s data cache. Use it to identify and retrieve records that have changed since your last fetch. For example, filtering `modifiedDate` to today will provide new records updated in Codat today. This date is populated for all data types except for attachments, balance sheets, company information, and profit & loss reports ([read more](https://docs.codat.io/using-the-api/modified-dates#modified-date)). In Codat's data model, dates and times are represented using the ISO 8601 standard. | +| `nominal_code` | *Optional[str]* | :heavy_minus_sign: | Code used to identify each nominal account for a business. | +| `overdraft_limit` | *Optional[Decimal]* | :heavy_minus_sign: | Pre-arranged overdraft limit of the account. The value is always positive. For example, an overdraftLimit of `1000` means that the balance of the account can go down to `-1000`. | +| `sort_code` | *Optional[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 | +| `supplemental_data` | [Optional[shared.SupplementalData]](../../models/shared/supplementaldata.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/createbankaccountresponsebankaccounttype.md b/sync-for-expenses/docs/models/shared/createbankaccountresponsebankaccounttype.md index fd4de5286..8bd21951d 100644 --- a/sync-for-expenses/docs/models/shared/createbankaccountresponsebankaccounttype.md +++ b/sync-for-expenses/docs/models/shared/createbankaccountresponsebankaccounttype.md @@ -1,22 +1,18 @@ -# CreateBankAccountResponseBankAccountType - -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_expenses.models.shared import CreateBankAccountResponseBankAccountType - -value = CreateBankAccountResponseBankAccountType.UNKNOWN -``` - - -## Values - -| Name | Value | -| --------- | --------- | -| `UNKNOWN` | Unknown | -| `CREDIT` | Credit | +# CreateBankAccountResponseBankAccountType + +## Example Usage + +```python +from codat_sync_for_expenses.models.shared import CreateBankAccountResponseBankAccountType + +value = CreateBankAccountResponseBankAccountType.UNKNOWN +``` + + +## Values + +| Name | Value | +| --------- | --------- | +| `UNKNOWN` | Unknown | +| `CREDIT` | Credit | | `DEBIT` | Debit | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/createconnectionrequest.md b/sync-for-expenses/docs/models/shared/createconnectionrequest.md new file mode 100644 index 000000000..dcf930d2f --- /dev/null +++ b/sync-for-expenses/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-expenses/docs/models/shared/createcustomerresponse.md b/sync-for-expenses/docs/models/shared/createcustomerresponse.md index 7bcb27ed0..32793c02f 100644 --- a/sync-for-expenses/docs/models/shared/createcustomerresponse.md +++ b/sync-for-expenses/docs/models/shared/createcustomerresponse.md @@ -1,21 +1,21 @@ -# CreateCustomerResponse - - -## 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` | [OptionalNullable[shared.AccountingCustomer]](../../models/shared/accountingcustomer.md) | :heavy_minus_sign: | N/A | | -| `data_connection_key` | *str* | :heavy_check_mark: | Unique identifier for a company's data connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | -| `data_type` | [Optional[shared.DataType]](../../models/shared/datatype.md) | :heavy_minus_sign: | Available data types | invoices | -| `error_message` | *OptionalNullable[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` | *OptionalNullable[int]* | :heavy_minus_sign: | Number of minutes the push operation must complete within before it times out. | | -| ~~`timeout_in_seconds`~~ | *OptionalNullable[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 +# CreateCustomerResponse + + +## 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: | The datetime when the push was completed, null if Pending. | | +| `data` | [OptionalNullable[shared.CreateCustomerResponseAllOfData]](../../models/shared/createcustomerresponseallofdata.md) | :heavy_minus_sign: | N/A | | +| `data_connection_key` | *str* | :heavy_check_mark: | Unique identifier for a company's data connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | +| `data_type` | [Optional[shared.DataType]](../../models/shared/datatype.md) | :heavy_minus_sign: | Available data types | invoices | +| `error_message` | *OptionalNullable[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: | The datetime when the push was requested. | | +| `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` | *OptionalNullable[int]* | :heavy_minus_sign: | Number of minutes the push operation must complete within before it times out. | | +| ~~`timeout_in_seconds`~~ | *OptionalNullable[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-expenses/docs/models/shared/createcustomerresponseallofdata.md b/sync-for-expenses/docs/models/shared/createcustomerresponseallofdata.md new file mode 100644 index 000000000..db2969f49 --- /dev/null +++ b/sync-for-expenses/docs/models/shared/createcustomerresponseallofdata.md @@ -0,0 +1,22 @@ +# CreateCustomerResponseAllOfData + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `addresses` | List[[shared.Items](../../models/shared/items.md)] | :heavy_minus_sign: | An array of Addresses. | +| `contact_name` | *Optional[str]* | :heavy_minus_sign: | Name of the main contact for the identified customer. | +| `contacts` | List[[shared.Contact](../../models/shared/contact.md)] | :heavy_minus_sign: | An array of Contacts. | +| `customer_name` | *Optional[str]* | :heavy_minus_sign: | Name of the customer as recorded in the accounting system, typically the company name. | +| `default_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. | +| `email_address` | *Optional[str]* | :heavy_minus_sign: | Email address the customer can be contacted by. | +| `id` | *Optional[str]* | :heavy_minus_sign: | Identifier for the customer, unique to the company in the accounting software. | +| `metadata` | [Optional[shared.Metadata]](../../models/shared/metadata.md) | :heavy_minus_sign: | N/A | +| `modified_date` | *Optional[str]* | :heavy_minus_sign: | The date when the record was last fetched from the accounting software, commerce software, or open banking provider and updated in Codat’s data cache. Use it to identify and retrieve records that have changed since your last fetch. For example, filtering `modifiedDate` to today will provide new records updated in Codat today. This date is populated for all data types except for attachments, balance sheets, company information, and profit & loss reports ([read more](https://docs.codat.io/using-the-api/modified-dates#modified-date)). In Codat's data model, dates and times are represented using the ISO 8601 standard. | +| `phone` | *Optional[str]* | :heavy_minus_sign: | Phone number the customer can be contacted by. | +| `registration_number` | *Optional[str]* | :heavy_minus_sign: | Company number. In the UK, this is typically the Companies House company registration number. | +| `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` | [shared.CustomerStatus](../../models/shared/customerstatus.md) | :heavy_check_mark: | Current state of the customer. | +| `supplemental_data` | [Optional[shared.SupplementalData]](../../models/shared/supplementaldata.md) | :heavy_minus_sign: | N/A | +| `tax_number` | *Optional[str]* | :heavy_minus_sign: | Company tax number. | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/createexpenseresponse.md b/sync-for-expenses/docs/models/shared/createexpenseresponse.md index 7a5d81b08..26d79ee06 100644 --- a/sync-for-expenses/docs/models/shared/createexpenseresponse.md +++ b/sync-for-expenses/docs/models/shared/createexpenseresponse.md @@ -1,8 +1,8 @@ -# CreateExpenseResponse - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +# CreateExpenseResponse + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | | `sync_id` | *Optional[str]* | :heavy_minus_sign: | Unique id of sync created | cd937d46-8e41-43a9-9477-a79158ffd98a | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/createreimbursableexpenseresponse.md b/sync-for-expenses/docs/models/shared/createreimbursableexpenseresponse.md index 437f5a2d3..259030861 100644 --- a/sync-for-expenses/docs/models/shared/createreimbursableexpenseresponse.md +++ b/sync-for-expenses/docs/models/shared/createreimbursableexpenseresponse.md @@ -1,8 +1,8 @@ -# CreateReimbursableExpenseResponse - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +# CreateReimbursableExpenseResponse + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | | `sync_id` | *Optional[str]* | :heavy_minus_sign: | Unique id of sync created | cd937d46-8e41-43a9-9477-a79158ffd98a | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/createsupplierresponse.md b/sync-for-expenses/docs/models/shared/createsupplierresponse.md index 14914734b..654c4450c 100644 --- a/sync-for-expenses/docs/models/shared/createsupplierresponse.md +++ b/sync-for-expenses/docs/models/shared/createsupplierresponse.md @@ -1,21 +1,21 @@ -# CreateSupplierResponse - - -## 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` | [OptionalNullable[shared.AccountingSupplier]](../../models/shared/accountingsupplier.md) | :heavy_minus_sign: | N/A | {
"id": "C520FFD4-F6F6-4FC2-A6D2-5D7088B2B14F",
"supplierName": "Kelly's Industrial Supplies",
"contactName": "Kelly's Industrial Supplies",
"emailAddress": "sales@kellysupplies.com",
"phone": "07999 999999",
"addresses": [
{
"type": "Billing",
"line1": "Unit 51",
"line2": "Bakersfield Industrial Estate",
"city": "Bakersfield",
"region": "California",
"country": "USA",
"postalcode": "93308"
}
],
"registrationNumber": "string",
"taxNumber": "string",
"status": "Unknown",
"defaultCurrency": "string",
"metadata": {
"isDeleted": true
},
"supplementalData": {
"content": {
"property1": {
"property1": null,
"property2": null
},
"property2": {
"property1": null,
"property2": null
}
}
},
"modifiedDate": "2022-10-23T00:00:00Z",
"sourceModifiedDate": "2022-10-23T00:00:00Z"
} | -| `data_connection_key` | *str* | :heavy_check_mark: | Unique identifier for a company's data connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | -| `data_type` | [Optional[shared.DataType]](../../models/shared/datatype.md) | :heavy_minus_sign: | Available data types | invoices | -| `error_message` | *OptionalNullable[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` | *OptionalNullable[int]* | :heavy_minus_sign: | Number of minutes the push operation must complete within before it times out. | | -| ~~`timeout_in_seconds`~~ | *OptionalNullable[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 +# CreateSupplierResponse + + +## 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: | The datetime when the push was completed, null if Pending. | | +| `data` | [OptionalNullable[shared.CreateSupplierResponseAllOfData]](../../models/shared/createsupplierresponseallofdata.md) | :heavy_minus_sign: | N/A | {
"id": "C520FFD4-F6F6-4FC2-A6D2-5D7088B2B14F",
"supplierName": "Kelly's Industrial Supplies",
"contactName": "Kelly's Industrial Supplies",
"emailAddress": "sales@kellysupplies.com",
"phone": "07999 999999",
"addresses": [
{
"type": "Billing",
"line1": "Unit 51",
"line2": "Bakersfield Industrial Estate",
"city": "Bakersfield",
"region": "California",
"country": "USA",
"postalcode": "93308"
}
],
"registrationNumber": "string",
"taxNumber": "string",
"status": "Unknown",
"defaultCurrency": "string",
"metadata": {
"isDeleted": true
},
"supplementalData": {
"content": {
"property1": {
"property1": null,
"property2": null
},
"property2": {
"property1": null,
"property2": null
}
}
},
"modifiedDate": "2022-10-23T00:00:00Z",
"sourceModifiedDate": "2022-10-23T00:00:00Z"
} | +| `data_connection_key` | *str* | :heavy_check_mark: | Unique identifier for a company's data connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | +| `data_type` | [Optional[shared.DataType]](../../models/shared/datatype.md) | :heavy_minus_sign: | Available data types | invoices | +| `error_message` | *OptionalNullable[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: | The datetime when the push was requested. | | +| `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` | *OptionalNullable[int]* | :heavy_minus_sign: | Number of minutes the push operation must complete within before it times out. | | +| ~~`timeout_in_seconds`~~ | *OptionalNullable[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-expenses/docs/models/shared/createsupplierresponseallofdata.md b/sync-for-expenses/docs/models/shared/createsupplierresponseallofdata.md new file mode 100644 index 000000000..b466c78ea --- /dev/null +++ b/sync-for-expenses/docs/models/shared/createsupplierresponseallofdata.md @@ -0,0 +1,21 @@ +# CreateSupplierResponseAllOfData + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `addresses` | List[[shared.Items](../../models/shared/items.md)] | :heavy_minus_sign: | An array of Addresses. | +| `contact_name` | *Optional[str]* | :heavy_minus_sign: | Name of the main contact for the supplier. | +| `default_currency` | *Optional[str]* | :heavy_minus_sign: | Default currency the supplier's transactional data is recorded in. | +| `email_address` | *Optional[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. | +| `metadata` | [Optional[shared.Metadata]](../../models/shared/metadata.md) | :heavy_minus_sign: | N/A | +| `modified_date` | *Optional[str]* | :heavy_minus_sign: | The date when the record was last fetched from the accounting software, commerce software, or open banking provider and updated in Codat’s data cache. Use it to identify and retrieve records that have changed since your last fetch. For example, filtering `modifiedDate` to today will provide new records updated in Codat today. This date is populated for all data types except for attachments, balance sheets, company information, and profit & loss reports ([read more](https://docs.codat.io/using-the-api/modified-dates#modified-date)). In Codat's data model, dates and times are represented using the ISO 8601 standard. | +| `phone` | *Optional[str]* | :heavy_minus_sign: | Phone number that the supplier may be contacted on. | +| `registration_number` | *Optional[str]* | :heavy_minus_sign: | Company number of the supplier. In the UK, this is typically the company registration number issued by Companies House. | +| `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` | [shared.SupplierStatus](../../models/shared/supplierstatus.md) | :heavy_check_mark: | N/A | +| `supplemental_data` | [Optional[shared.SupplementalData]](../../models/shared/supplementaldata.md) | :heavy_minus_sign: | N/A | +| `supplier_name` | *Optional[str]* | :heavy_minus_sign: | Name of the supplier as recorded in the accounting system, typically the company name. | +| `tax_number` | *Optional[str]* | :heavy_minus_sign: | Supplier's company tax number. | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/currentstatus.md b/sync-for-expenses/docs/models/shared/currentstatus.md new file mode 100644 index 000000000..383123b21 --- /dev/null +++ b/sync-for-expenses/docs/models/shared/currentstatus.md @@ -0,0 +1,36 @@ +# CurrentStatus + +## Example Usage + +```python +from codat_sync_for_expenses.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-expenses/docs/models/shared/customer.md b/sync-for-expenses/docs/models/shared/customer.md index c82c02896..ec9576bf3 100644 --- a/sync-for-expenses/docs/models/shared/customer.md +++ b/sync-for-expenses/docs/models/shared/customer.md @@ -1,29 +1,29 @@ -# Customer - -## Overview - -A customer is a person or organisation that buys goods or services. From the Customers endpoints, you can retrieve a [list of all the customers of a company](https://api.codat.io/swagger/index.html#/Customers/get_companies__companyId__data_customers). - -Customers' data links to accounts receivable [invoices](https://docs.codat.io/sync-for-expenses-api#/schemas/Invoice). - - - -## Fields - -| Field | Type | Required | Description | Example | -| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `addresses` | List[[shared.Items](../../models/shared/items.md)] | :heavy_minus_sign: | An array of Addresses. | | -| `contact_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the main contact for the identified customer. | | -| `contacts` | List[[shared.Contact](../../models/shared/contact.md)] | :heavy_minus_sign: | An array of Contacts. | | -| `customer_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the customer as recorded in the accounting system, typically the company name. | | -| `default_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 | -| `email_address` | *OptionalNullable[str]* | :heavy_minus_sign: | Email address the customer can be contacted by. | | -| `id` | *Optional[str]* | :heavy_minus_sign: | Identifier for the customer, unique to the company in the accounting software. | | -| `metadata` | [Optional[shared.Metadata]](../../models/shared/metadata.md) | :heavy_minus_sign: | N/A | | -| `modified_date` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `phone` | *OptionalNullable[str]* | :heavy_minus_sign: | Phone number the customer can be contacted by. | | -| `registration_number` | *OptionalNullable[str]* | :heavy_minus_sign: | Company number. In the UK, this is typically the Companies House company registration number. | | -| `source_modified_date` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `status` | [shared.CustomerStatus](../../models/shared/customerstatus.md) | :heavy_check_mark: | Status of customer. | | -| `supplemental_data` | [Optional[shared.SupplementalData]](../../models/shared/supplementaldata.md) | :heavy_minus_sign: | Supplemental data is additional data you can include in our standard data types.

It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. | | +# Customer + +## Overview + +A customer is a person or organisation that buys goods or services. From the Customers endpoints, you can retrieve a [list of all the customers of a company](https://api.codat.io/swagger/index.html#/Customers/get_companies__companyId__data_customers). + +Customers' data links to accounts receivable [invoices](https://docs.codat.io/sync-for-expenses-api#/schemas/Invoice). + + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `addresses` | List[[shared.Items](../../models/shared/items.md)] | :heavy_minus_sign: | An array of Addresses. | | +| `contact_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the main contact for the identified customer. | | +| `contacts` | List[[shared.Contact](../../models/shared/contact.md)] | :heavy_minus_sign: | An array of Contacts. | | +| `customer_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the customer as recorded in the accounting system, typically the company name. | | +| `default_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 | +| `email_address` | *OptionalNullable[str]* | :heavy_minus_sign: | Email address the customer can be contacted by. | | +| `id` | *Optional[str]* | :heavy_minus_sign: | Identifier for the customer, unique to the company in the accounting software. | | +| `metadata` | [Optional[shared.Metadata]](../../models/shared/metadata.md) | :heavy_minus_sign: | N/A | | +| `modified_date` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `phone` | *OptionalNullable[str]* | :heavy_minus_sign: | Phone number the customer can be contacted by. | | +| `registration_number` | *OptionalNullable[str]* | :heavy_minus_sign: | Company number. In the UK, this is typically the Companies House company registration number. | | +| `source_modified_date` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `status` | [shared.CustomerStatus](../../models/shared/customerstatus.md) | :heavy_check_mark: | Status of customer. | | +| `supplemental_data` | [Optional[shared.SupplementalData]](../../models/shared/supplementaldata.md) | :heavy_minus_sign: | Supplemental data is additional data you can include in our standard data types.

It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. | | | `tax_number` | *OptionalNullable[str]* | :heavy_minus_sign: | Company tax number. | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/customerdetails.md b/sync-for-expenses/docs/models/shared/customerdetails.md index a9f2451b9..b3bfc7b71 100644 --- a/sync-for-expenses/docs/models/shared/customerdetails.md +++ b/sync-for-expenses/docs/models/shared/customerdetails.md @@ -1,8 +1,8 @@ -# CustomerDetails - - -## Fields - -| Field | Type | Required | Description | -| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | +# CustomerDetails + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | | `id` | *Optional[str]* | :heavy_minus_sign: | Identifier for the customer, unique to the company in the accounting software. | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/customers.md b/sync-for-expenses/docs/models/shared/customers.md index 5ebaa24c1..937deac35 100644 --- a/sync-for-expenses/docs/models/shared/customers.md +++ b/sync-for-expenses/docs/models/shared/customers.md @@ -1,12 +1,12 @@ -# Customers - - -## 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[[Nullable[shared.Customer]](../../models/shared/customer.md)] | :heavy_minus_sign: | N/A | | +# Customers + + +## 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[[Nullable[shared.Customer]](../../models/shared/customer.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-expenses/docs/models/shared/customerstatus.md b/sync-for-expenses/docs/models/shared/customerstatus.md index a4cdc76a6..b518e7933 100644 --- a/sync-for-expenses/docs/models/shared/customerstatus.md +++ b/sync-for-expenses/docs/models/shared/customerstatus.md @@ -1,20 +1,18 @@ -# CustomerStatus - -Status of customer. - -## Example Usage - -```python -from codat_sync_for_expenses.models.shared import CustomerStatus - -value = CustomerStatus.UNKNOWN -``` - - -## Values - -| Name | Value | -| ---------- | ---------- | -| `UNKNOWN` | Unknown | -| `ACTIVE` | Active | +# CustomerStatus + +## Example Usage + +```python +from codat_sync_for_expenses.models.shared import CustomerStatus + +value = CustomerStatus.UNKNOWN +``` + + +## Values + +| Name | Value | +| ---------- | ---------- | +| `UNKNOWN` | Unknown | +| `ACTIVE` | Active | | `ARCHIVED` | Archived | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/dataconnectionerror.md b/sync-for-expenses/docs/models/shared/dataconnectionerror.md index 33b523477..33424d8c2 100644 --- a/sync-for-expenses/docs/models/shared/dataconnectionerror.md +++ b/sync-for-expenses/docs/models/shared/dataconnectionerror.md @@ -1,13 +1,13 @@ -# 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 +# DataConnectionError + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | +| `error_message` | *Optional[str]* | :heavy_minus_sign: | A message about a error returned by Codat. | +| `errored_on_utc` | *Optional[str]* | :heavy_minus_sign: | Date of the transfer transaction as recorded in the accounting software. | +| `resolved_on_utc` | *Optional[str]* | :heavy_minus_sign: | The datetime in Utc that the error was resolved. | +| `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-expenses/docs/models/shared/dataconnectionstatus.md b/sync-for-expenses/docs/models/shared/dataconnectionstatus.md index 813579bf0..ea1cc4e4e 100644 --- a/sync-for-expenses/docs/models/shared/dataconnectionstatus.md +++ b/sync-for-expenses/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_expenses.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_expenses.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-expenses/docs/models/shared/datasetstatus.md b/sync-for-expenses/docs/models/shared/datasetstatus.md index 40804df7e..4118c3034 100644 --- a/sync-for-expenses/docs/models/shared/datasetstatus.md +++ b/sync-for-expenses/docs/models/shared/datasetstatus.md @@ -1,38 +1,38 @@ -# DatasetStatus - -The current status of the dataset. - -## Example Usage - -```python -from codat_sync_for_expenses.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 | +# DatasetStatus + +The current status of the dataset. + +## Example Usage + +```python +from codat_sync_for_expenses.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-expenses/docs/models/shared/datastatus.md b/sync-for-expenses/docs/models/shared/datastatus.md index c89b47244..17ae0f371 100644 --- a/sync-for-expenses/docs/models/shared/datastatus.md +++ b/sync-for-expenses/docs/models/shared/datastatus.md @@ -1,14 +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` | [shared.Status](../../models/shared/status.md) | :heavy_check_mark: | The current status of the dataset. | | -| `data_type` | [shared.DataTypes](../../models/shared/datatypes.md) | :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 +# DataStatus + +Describes the state of data in the Codat cache for a company and data type + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | +| `current_status` | [shared.Status](../../models/shared/status.md) | :heavy_check_mark: | The current status of the dataset. | | +| `data_type` | [shared.DataTypes](../../models/shared/datatypes.md) | :heavy_check_mark: | Available data types | invoices | +| `last_successful_sync` | *Optional[str]* | :heavy_minus_sign: | Date of the transfer transaction as recorded in the accounting software. | | +| `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-expenses/docs/models/shared/datastatuses.md b/sync-for-expenses/docs/models/shared/datastatuses.md new file mode 100644 index 000000000..9a8cf4cb8 --- /dev/null +++ b/sync-for-expenses/docs/models/shared/datastatuses.md @@ -0,0 +1,50 @@ +# DataStatuses + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------- | +| `account_transactions` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `balance_sheet` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `bank_accounts` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `bank_transactions` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `banking_account_balances` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `banking_accounts` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `banking_transaction_categories` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `banking_transactions` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `bill_credit_notes` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `bill_payments` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `bills` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `cash_flow_statement` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `chart_of_accounts` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `commerce_company_info` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `commerce_customers` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `commerce_disputes` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `commerce_locations` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `commerce_orders` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `commerce_payment_methods` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `commerce_payments` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `commerce_product_categories` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `commerce_products` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `commerce_tax_components` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `commerce_transactions` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `company` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `credit_notes` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `customers` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `direct_costs` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `direct_incomes` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `invoices` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `item_receipts` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `items` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `journal_entries` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `journals` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `payment_methods` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `payments` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `profit_and_loss` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `purchase_orders` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `sales_orders` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `suppliers` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `tax_rates` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `tracking_categories` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | +| `transfers` | [Optional[shared.DataStatus]](../../models/shared/datastatus.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/datatype.md b/sync-for-expenses/docs/models/shared/datatype.md index 2f337d67b..5aedaeef5 100644 --- a/sync-for-expenses/docs/models/shared/datatype.md +++ b/sync-for-expenses/docs/models/shared/datatype.md @@ -1,60 +1,75 @@ -# DataType - -Available data types - -## Example Usage - -```python -from codat_sync_for_expenses.models.shared import DataType - -value = DataType.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 +# DataType + +Available data types + +## Example Usage + +```python +from codat_sync_for_expenses.models.shared import DataType + +value = DataType.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_MINUS_ACCOUNT_BALANCES` | banking-accountBalances | +| `BANKING_ACCOUNT_BALANCES` | banking-accountBalances | +| `BANKING_MINUS_ACCOUNTS` | banking-accounts | +| `BANKING_ACCOUNTS` | banking-accounts | +| `BANKING_MINUS_TRANSACTION_CATEGORIES` | banking-transactionCategories | +| `BANKING_TRANSACTION_CATEGORIES` | banking-transactionCategories | +| `BANKING_MINUS_TRANSACTIONS` | banking-transactions | +| `BANKING_TRANSACTIONS` | banking-transactions | +| `COMMERCE_MINUS_COMPANY_INFO` | commerce-companyInfo | +| `COMMERCE_COMPANY_INFO` | commerce-companyInfo | +| `COMMERCE_MINUS_CUSTOMERS` | commerce-customers | +| `COMMERCE_CUSTOMERS` | commerce-customers | +| `COMMERCE_MINUS_DISPUTES` | commerce-disputes | +| `COMMERCE_DISPUTES` | commerce-disputes | +| `COMMERCE_MINUS_LOCATIONS` | commerce-locations | +| `COMMERCE_LOCATIONS` | commerce-locations | +| `COMMERCE_MINUS_ORDERS` | commerce-orders | +| `COMMERCE_ORDERS` | commerce-orders | +| `COMMERCE_MINUS_PAYMENT_METHODS` | commerce-paymentMethods | +| `COMMERCE_PAYMENT_METHODS` | commerce-paymentMethods | +| `COMMERCE_MINUS_PAYMENTS` | commerce-payments | +| `COMMERCE_PAYMENTS` | commerce-payments | +| `COMMERCE_MINUS_PRODUCT_CATEGORIES` | commerce-productCategories | +| `COMMERCE_PRODUCT_CATEGORIES` | commerce-productCategories | +| `COMMERCE_MINUS_PRODUCTS` | commerce-products | +| `COMMERCE_PRODUCTS` | commerce-products | +| `COMMERCE_MINUS_TAX_COMPONENTS` | commerce-taxComponents | +| `COMMERCE_TAX_COMPONENTS` | commerce-taxComponents | +| `COMMERCE_MINUS_TRANSACTIONS` | commerce-transactions | +| `COMMERCE_TRANSACTIONS` | commerce-transactions | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/datatypes.md b/sync-for-expenses/docs/models/shared/datatypes.md index 5d7b8f590..81ace5c5a 100644 --- a/sync-for-expenses/docs/models/shared/datatypes.md +++ b/sync-for-expenses/docs/models/shared/datatypes.md @@ -1,60 +1,60 @@ -# DataTypes - -Available data types - -## Example Usage - -```python -from codat_sync_for_expenses.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 | +# DataTypes + +Available data types + +## Example Usage + +```python +from codat_sync_for_expenses.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-expenses/docs/models/shared/errormessage.md b/sync-for-expenses/docs/models/shared/errormessage.md new file mode 100644 index 000000000..425e22bbf --- /dev/null +++ b/sync-for-expenses/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-expenses/docs/models/shared/errorstatus.md b/sync-for-expenses/docs/models/shared/errorstatus.md index 1c9e3e20e..18e6a97c6 100644 --- a/sync-for-expenses/docs/models/shared/errorstatus.md +++ b/sync-for-expenses/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_expenses.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_expenses.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-expenses/docs/models/shared/errorvalidation.md b/sync-for-expenses/docs/models/shared/errorvalidation.md index 122badd9d..618d40ff2 100644 --- a/sync-for-expenses/docs/models/shared/errorvalidation.md +++ b/sync-for-expenses/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-expenses/docs/models/shared/errorvalidationitem.md b/sync-for-expenses/docs/models/shared/errorvalidationitem.md index fca2ef14a..a2ea37332 100644 --- a/sync-for-expenses/docs/models/shared/errorvalidationitem.md +++ b/sync-for-expenses/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-expenses/docs/models/shared/expensecontactref.md b/sync-for-expenses/docs/models/shared/expensecontactref.md index 7889b747d..54e545225 100644 --- a/sync-for-expenses/docs/models/shared/expensecontactref.md +++ b/sync-for-expenses/docs/models/shared/expensecontactref.md @@ -1,9 +1,9 @@ -# ExpenseContactRef - - -## Fields - -| Field | Type | Required | Description | Example | -| -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -| `id` | *str* | :heavy_check_mark: | Identifier of supplier or customer. | 40e3e57c-2322-4898-966c-ca41adfd23fd | +# ExpenseContactRef + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | +| `id` | *str* | :heavy_check_mark: | Identifier of supplier or customer. | 40e3e57c-2322-4898-966c-ca41adfd23fd | | `type` | [Optional[shared.ExpenseContactRefType]](../../models/shared/expensecontactreftype.md) | :heavy_minus_sign: | The type of contact. | Supplier | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/expensecontactreftype.md b/sync-for-expenses/docs/models/shared/expensecontactreftype.md index 8542b2e03..5154dc900 100644 --- a/sync-for-expenses/docs/models/shared/expensecontactreftype.md +++ b/sync-for-expenses/docs/models/shared/expensecontactreftype.md @@ -1,18 +1,18 @@ -# ExpenseContactRefType - -The type of contact. - -## Example Usage - -```python -from codat_sync_for_expenses.models.shared import ExpenseContactRefType - -value = ExpenseContactRefType.SUPPLIER -``` - - -## Values - -| Name | Value | -| ---------- | ---------- | +# ExpenseContactRefType + +The type of contact. + +## Example Usage + +```python +from codat_sync_for_expenses.models.shared import ExpenseContactRefType + +value = ExpenseContactRefType.SUPPLIER +``` + + +## Values + +| Name | Value | +| ---------- | ---------- | | `SUPPLIER` | Supplier | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/expensessyncwebhook.md b/sync-for-expenses/docs/models/shared/expensessyncwebhook.md index 7b8e3b103..565bb2ecc 100644 --- a/sync-for-expenses/docs/models/shared/expensessyncwebhook.md +++ b/sync-for-expenses/docs/models/shared/expensessyncwebhook.md @@ -1,11 +1,11 @@ -# ExpensesSyncWebhook - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `event_type` | *Optional[str]* | :heavy_minus_sign: | The type of event. | **Example 1:** expenses.sync.successful
**Example 2:** expenses.sync.unsuccessful | -| `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. | ba29118f-5406-4e59-b05c-ba307ca38d01 | -| `payload` | [Optional[shared.ExpensesSyncWebhookPayload]](../../models/shared/expensessyncwebhookpayload.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file +# ExpensesSyncWebhook + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | +| `event_type` | *Optional[str]* | :heavy_minus_sign: | The type of event. | **Example 1:** expenses.sync.successful
**Example 2:** expenses.sync.unsuccessful | +| `generated_date` | *Optional[str]* | :heavy_minus_sign: | The date time in UTC the event was generated in Codat. | | +| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of the event. | ba29118f-5406-4e59-b05c-ba307ca38d01 | +| `payload` | [Optional[shared.ExpensesSyncWebhookPayload]](../../models/shared/expensessyncwebhookpayload.md) | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/expensessyncwebhookpayload.md b/sync-for-expenses/docs/models/shared/expensessyncwebhookpayload.md index e849000df..c09f7be58 100644 --- a/sync-for-expenses/docs/models/shared/expensessyncwebhookpayload.md +++ b/sync-for-expenses/docs/models/shared/expensessyncwebhookpayload.md @@ -1,10 +1,10 @@ -# ExpensesSyncWebhookPayload - - -## Fields - -| Field | Type | Required | Description | -| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | -| `reference_company` | [Optional[shared.CompanyReference]](../../models/shared/companyreference.md) | :heavy_minus_sign: | N/A | -| `sync_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of the sync. | +# ExpensesSyncWebhookPayload + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | +| `reference_company` | [Optional[shared.CompanyReference]](../../models/shared/companyreference.md) | :heavy_minus_sign: | N/A | +| `sync_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of the sync. | | `transactions` | List[[shared.Transaction](../../models/shared/transaction.md)] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/expensessyncwebhookstatus.md b/sync-for-expenses/docs/models/shared/expensessyncwebhookstatus.md new file mode 100644 index 000000000..2d08a0e8e --- /dev/null +++ b/sync-for-expenses/docs/models/shared/expensessyncwebhookstatus.md @@ -0,0 +1,20 @@ +# ExpensesSyncWebhookStatus + +## Example Usage + +```python +from codat_sync_for_expenses.models.shared import ExpensesSyncWebhookStatus + +value = ExpensesSyncWebhookStatus.UNKNOWN +``` + + +## Values + +| Name | Value | +| ------------ | ------------ | +| `UNKNOWN` | Unknown | +| `PUSH_ERROR` | PushError | +| `COMPLETED` | Completed | +| `FAILED` | Failed | +| `PENDING` | Pending | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/expensetransaction.md b/sync-for-expenses/docs/models/shared/expensetransaction.md index 9f6ab23de..807fc3c46 100644 --- a/sync-for-expenses/docs/models/shared/expensetransaction.md +++ b/sync-for-expenses/docs/models/shared/expensetransaction.md @@ -1,19 +1,19 @@ -# ExpenseTransaction - - -## Fields - -| Field | Type | Required | Description | Example | -| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `bank_account_ref` | [Optional[shared.BankAccountReference]](../../models/shared/bankaccountreference.md) | :heavy_minus_sign: | N/A | | -| `contact_ref` | [Optional[shared.ExpenseContactRef]](../../models/shared/expensecontactref.md) | :heavy_minus_sign: | N/A | | -| `currency` | *str* | :heavy_check_mark: | Currency the transaction was recorded in. | GBP | -| `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. \| | | -| `id` | *str* | :heavy_check_mark: | Your unique identifier for the transaction. | 4d7c6929-7770-412b-91bb-44d3bc71d111 | -| `issue_date` | *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 | -| `lines` | List[[shared.ExpenseTransactionLine](../../models/shared/expensetransactionline.md)] | :heavy_minus_sign: | Array of transaction lines. | | -| `merchant_name` | *Optional[str]* | :heavy_minus_sign: | Name of the merchant where the purchase took place | Amazon UK | -| `notes` | *Optional[str]* | :heavy_minus_sign: | Any private, company notes about the transaction. | APPLE.COM/BILL - 09001077498 - Card Ending: 4590 | -| `post_as_draft` | *OptionalNullable[bool]* | :heavy_minus_sign: | This optional property, when set to true, posts the transaction to a drafted state. Note that postAsDraft is only supported in Microsoft Dynamics 365 Business Central. | | -| `reference` | *OptionalNullable[str]* | :heavy_minus_sign: | User-friendly reference for the expense transaction. | | +# ExpenseTransaction + + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `bank_account_ref` | [Optional[shared.BankAccountReference]](../../models/shared/bankaccountreference.md) | :heavy_minus_sign: | N/A | | +| `contact_ref` | [Optional[shared.ExpenseContactRef]](../../models/shared/expensecontactref.md) | :heavy_minus_sign: | Supplier or customer for the purchase to be associated to. | | +| `currency` | *str* | :heavy_check_mark: | Currency the transaction was recorded in. | GBP | +| `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. \| | | +| `id` | *str* | :heavy_check_mark: | Your unique identifier for the transaction. | 4d7c6929-7770-412b-91bb-44d3bc71d111 | +| `issue_date` | *str* | :heavy_check_mark: | Date of the transaction was recorded. | | +| `lines` | List[[shared.ExpenseTransactionLine](../../models/shared/expensetransactionline.md)] | :heavy_minus_sign: | Array of transaction lines. | | +| `merchant_name` | *Optional[str]* | :heavy_minus_sign: | Name of the merchant where the purchase took place | Amazon UK | +| `notes` | *Optional[str]* | :heavy_minus_sign: | Any private, company notes about the transaction. | APPLE.COM/BILL - 09001077498 - Card Ending: 4590 | +| `post_as_draft` | *OptionalNullable[bool]* | :heavy_minus_sign: | This optional property, when set to true, posts the transaction to a drafted state. Note that postAsDraft is only supported in Microsoft Dynamics 365 Business Central. | | +| `reference` | *OptionalNullable[str]* | :heavy_minus_sign: | User-friendly reference for the expense transaction. | | | `type` | [shared.ExpenseTransactionType](../../models/shared/expensetransactiontype.md) | :heavy_check_mark: | The type of transaction. | Payment | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/expensetransactionline.md b/sync-for-expenses/docs/models/shared/expensetransactionline.md index 90501ae82..7a9dc2a92 100644 --- a/sync-for-expenses/docs/models/shared/expensetransactionline.md +++ b/sync-for-expenses/docs/models/shared/expensetransactionline.md @@ -1,14 +1,14 @@ -# ExpenseTransactionLine - - -## Fields - -| Field | Type | Required | Description | Example | -| --------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `account_ref` | [Optional[shared.RecordRef]](../../models/shared/recordref.md) | :heavy_minus_sign: | N/A | | -| `invoice_to` | [OptionalNullable[shared.InvoiceTo]](../../models/shared/invoiceto.md) | :heavy_minus_sign: | Unique identifier for the customer billed for the transaction. The `invoiceTo` object is currently supported only for QuickBooks Online and QuickBooks Desktop. | | -| `item_ref` | [OptionalNullable[shared.ItemRef]](../../models/shared/itemref.md) | :heavy_minus_sign: | N/A | | -| `net_amount` | *Decimal* | :heavy_check_mark: | Amount of the line, exclusive of tax. | 100 | -| `tax_amount` | *Optional[Decimal]* | :heavy_minus_sign: | Amount of tax for the line. | 20 | -| `tax_rate_ref` | [Optional[shared.RecordRef]](../../models/shared/recordref.md) | :heavy_minus_sign: | N/A | | -| `tracking_refs` | List[[shared.TrackingRef](../../models/shared/trackingref.md)] | :heavy_minus_sign: | N/A | | \ No newline at end of file +# ExpenseTransactionLine + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `account_ref` | [Optional[shared.RecordRef]](../../models/shared/recordref.md) | :heavy_minus_sign: | The `accountRef` contains the `id` of the account the transaction is against. The `accountRef` object is required for all integrations except QBD which currently supports either itemRef or accountRef. | | +| `invoice_to` | [OptionalNullable[shared.InvoiceTo]](../../models/shared/invoiceto.md) | :heavy_minus_sign: | Unique identifier for the customer billed for the transaction. The `invoiceTo` object is currently supported only for QuickBooks Online and QuickBooks Desktop. | | +| `item_ref` | [OptionalNullable[shared.ItemRef]](../../models/shared/itemref.md) | :heavy_minus_sign: | N/A | | +| `net_amount` | *Decimal* | :heavy_check_mark: | Amount of the line, exclusive of tax. | 100 | +| `tax_amount` | *Optional[Decimal]* | :heavy_minus_sign: | Amount of tax for the line. | 20 | +| `tax_rate_ref` | [Optional[shared.RecordRef]](../../models/shared/recordref.md) | :heavy_minus_sign: | N/A | | +| `tracking_refs` | List[[shared.TrackingRef](../../models/shared/trackingref.md)] | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/expensetransactiontype.md b/sync-for-expenses/docs/models/shared/expensetransactiontype.md index 186aa20ae..00326e38c 100644 --- a/sync-for-expenses/docs/models/shared/expensetransactiontype.md +++ b/sync-for-expenses/docs/models/shared/expensetransactiontype.md @@ -1,21 +1,19 @@ -# ExpenseTransactionType - -The type of transaction. - -## Example Usage - -```python -from codat_sync_for_expenses.models.shared import ExpenseTransactionType - -value = ExpenseTransactionType.PAYMENT -``` - - -## Values - -| Name | Value | -| ------------ | ------------ | -| `PAYMENT` | Payment | -| `REFUND` | Refund | -| `REWARD` | Reward | +# ExpenseTransactionType + +## Example Usage + +```python +from codat_sync_for_expenses.models.shared import ExpenseTransactionType + +value = ExpenseTransactionType.PAYMENT +``` + + +## Values + +| Name | Value | +| ------------ | ------------ | +| `PAYMENT` | Payment | +| `REFUND` | Refund | +| `REWARD` | Reward | | `CHARGEBACK` | Chargeback | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/halref.md b/sync-for-expenses/docs/models/shared/halref.md index 94c6476ff..75aa86923 100644 --- a/sync-for-expenses/docs/models/shared/halref.md +++ b/sync-for-expenses/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-expenses/docs/models/shared/integrationtype.md b/sync-for-expenses/docs/models/shared/integrationtype.md index 8d9afc862..6a07ccc9e 100644 --- a/sync-for-expenses/docs/models/shared/integrationtype.md +++ b/sync-for-expenses/docs/models/shared/integrationtype.md @@ -1,19 +1,19 @@ -# IntegrationType - -Type of transaction that has been processed e.g. Expense or Bank Feed. - -## Example Usage - -```python -from codat_sync_for_expenses.models.shared import IntegrationType - -value = IntegrationType.EXPENSES -``` - - -## Values - -| Name | Value | -| ----------- | ----------- | -| `EXPENSES` | expenses | +# IntegrationType + +Type of transaction that has been processed e.g. Expense or Bank Feed. + +## Example Usage + +```python +from codat_sync_for_expenses.models.shared import IntegrationType + +value = IntegrationType.EXPENSES +``` + + +## Values + +| Name | Value | +| ----------- | ----------- | +| `EXPENSES` | expenses | | `BANKFEEDS` | bankfeeds | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/invoiceto.md b/sync-for-expenses/docs/models/shared/invoiceto.md index 7e1b8850e..ff0f9038b 100644 --- a/sync-for-expenses/docs/models/shared/invoiceto.md +++ b/sync-for-expenses/docs/models/shared/invoiceto.md @@ -1,11 +1,11 @@ -# InvoiceTo - -Unique identifier for the customer billed for the transaction. The `invoiceTo` object is currently supported only for QuickBooks Online and QuickBooks Desktop. - - -## Fields - -| Field | Type | Required | Description | Example | -| ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | -| `id` | *Optional[str]* | :heavy_minus_sign: | identifier of customer. | 80000002-1674552702 | +# InvoiceTo + +Unique identifier for the customer billed for the transaction. The `invoiceTo` object is currently supported only for QuickBooks Online and QuickBooks Desktop. + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | +| `id` | *Optional[str]* | :heavy_minus_sign: | identifier of customer. | 80000002-1674552702 | | `type` | [Optional[shared.InvoiceToType]](../../models/shared/invoicetotype.md) | :heavy_minus_sign: | The type of contact. | customer | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/invoicetotype.md b/sync-for-expenses/docs/models/shared/invoicetotype.md index 8977ebc04..57fc1778a 100644 --- a/sync-for-expenses/docs/models/shared/invoicetotype.md +++ b/sync-for-expenses/docs/models/shared/invoicetotype.md @@ -1,18 +1,16 @@ -# InvoiceToType - -The type of contact. - -## Example Usage - -```python -from codat_sync_for_expenses.models.shared import InvoiceToType - -value = InvoiceToType.CUSTOMER -``` - - -## Values - -| Name | Value | -| ---------- | ---------- | +# InvoiceToType + +## Example Usage + +```python +from codat_sync_for_expenses.models.shared import InvoiceToType + +value = InvoiceToType.CUSTOMER +``` + + +## Values + +| Name | Value | +| ---------- | ---------- | | `CUSTOMER` | customer | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/itemref.md b/sync-for-expenses/docs/models/shared/itemref.md index 502d43740..f1cad018e 100644 --- a/sync-for-expenses/docs/models/shared/itemref.md +++ b/sync-for-expenses/docs/models/shared/itemref.md @@ -1,8 +1,8 @@ -# ItemRef - - -## Fields - -| Field | Type | Required | Description | Example | -| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +# ItemRef + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for the item associated with the transaction. The `itemRef` object is currently supported only for QuickBooks Desktop. You can specify either `itemRef` or `accountRef`, but not both. | 80000002-1675158984 | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/items.md b/sync-for-expenses/docs/models/shared/items.md index 740e1b1b9..3e85b0fcc 100644 --- a/sync-for-expenses/docs/models/shared/items.md +++ b/sync-for-expenses/docs/models/shared/items.md @@ -1,14 +1,14 @@ -# Items - - -## 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 customer 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. | -| `postal_code` | *OptionalNullable[str]* | :heavy_minus_sign: | Postal code or zip code. | -| `region` | *OptionalNullable[str]* | :heavy_minus_sign: | Region of the customer address. | -| `type` | [shared.AccountingAddressType](../../models/shared/accountingaddresstype.md) | :heavy_check_mark: | The type of the address | \ No newline at end of file +# Items + + +## 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 customer 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. | +| `postal_code` | *OptionalNullable[str]* | :heavy_minus_sign: | Postal code or zip code. | +| `region` | *OptionalNullable[str]* | :heavy_minus_sign: | Region of the customer address. | +| `type` | [shared.AccountingAddressType](../../models/shared/accountingaddresstype.md) | :heavy_check_mark: | N/A | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/links.md b/sync-for-expenses/docs/models/shared/links.md index 5f80d2652..b91889951 100644 --- a/sync-for-expenses/docs/models/shared/links.md +++ b/sync-for-expenses/docs/models/shared/links.md @@ -1,11 +1,11 @@ -# 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 | +# 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-expenses/docs/models/shared/mappingoptions.md b/sync-for-expenses/docs/models/shared/mappingoptions.md index 3b366f7dd..b189468a8 100644 --- a/sync-for-expenses/docs/models/shared/mappingoptions.md +++ b/sync-for-expenses/docs/models/shared/mappingoptions.md @@ -1,11 +1,12 @@ -# MappingOptions - - -## Fields - -| Field | Type | Required | Description | Example | -| ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | -| `accounts` | List[[shared.AccountMappingInfo](../../models/shared/accountmappinginfo.md)] | :heavy_minus_sign: | Array of available accounts for mapping. | | -| `expense_provider` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the expense integration. | Partner Expense | -| `tax_rates` | List[[shared.TaxRateMappingInfo](../../models/shared/taxratemappinginfo.md)] | :heavy_minus_sign: | Array of available tax rates for mapping. | | +# MappingOptions + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | +| `accounts` | List[[shared.AccountMappingInfo](../../models/shared/accountmappinginfo.md)] | :heavy_minus_sign: | Array of available accounts for mapping. | | +| `additional_properties` | Dict[str, *Any*] | :heavy_check_mark: | N/A | | +| `expense_provider` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the expense integration. | Partner Expense | +| `tax_rates` | List[[shared.TaxRateMappingInfo](../../models/shared/taxratemappinginfo.md)] | :heavy_minus_sign: | Array of available tax rates for mapping. | | | `tracking_categories` | List[[shared.TrackingCategoryMappingInfo](../../models/shared/trackingcategorymappinginfo.md)] | :heavy_minus_sign: | Array of available tracking categories for mapping. | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/metadata.md b/sync-for-expenses/docs/models/shared/metadata.md index 8fb4a6e5c..0b4a50ce8 100644 --- a/sync-for-expenses/docs/models/shared/metadata.md +++ b/sync-for-expenses/docs/models/shared/metadata.md @@ -1,8 +1,8 @@ -# Metadata - - -## Fields - -| Field | Type | Required | Description | -| ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | +# Metadata + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | | `is_deleted` | *OptionalNullable[bool]* | :heavy_minus_sign: | Indicates whether the record has been deleted in the third-party system this record originated from. | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/model3.md b/sync-for-expenses/docs/models/shared/model3.md new file mode 100644 index 000000000..444de48e8 --- /dev/null +++ b/sync-for-expenses/docs/models/shared/model3.md @@ -0,0 +1,9 @@ +# Model3 + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `modified_date` | *Optional[str]* | :heavy_minus_sign: | The date when the record was last fetched from the accounting software, commerce software, or open banking provider and updated in Codat’s data cache. Use it to identify and retrieve records that have changed since your last fetch. For example, filtering `modifiedDate` to today will provide new records updated in Codat today. This date is populated for all data types except for attachments, balance sheets, company information, and profit & loss reports ([read more](https://docs.codat.io/using-the-api/modified-dates#modified-date)). In Codat's data model, dates and times are represented using the ISO 8601 standard. | +| `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. | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/paginginfo.md b/sync-for-expenses/docs/models/shared/paginginfo.md new file mode 100644 index 000000000..b72226e79 --- /dev/null +++ b/sync-for-expenses/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-expenses/docs/models/shared/phone.md b/sync-for-expenses/docs/models/shared/phone.md deleted file mode 100644 index ea0d84c06..000000000 --- a/sync-for-expenses/docs/models/shared/phone.md +++ /dev/null @@ -1,9 +0,0 @@ -# Phone - - -## Fields - -| Field | Type | Required | Description | Example | -| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -| `number` | *OptionalNullable[str]* | :heavy_minus_sign: | A phone number. | **Example 1:** +44 25691 154789
**Example 2:** (877) 492-8687
**Example 3:** 01224 658 999 | -| `type` | [shared.CompanyInformationType](../../models/shared/companyinformationtype.md) | :heavy_check_mark: | The type of phone number | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/phonenumberitems.md b/sync-for-expenses/docs/models/shared/phonenumberitems.md index 9fa79fec0..d21990832 100644 --- a/sync-for-expenses/docs/models/shared/phonenumberitems.md +++ b/sync-for-expenses/docs/models/shared/phonenumberitems.md @@ -1,9 +1,9 @@ -# PhoneNumberItems - - -## Fields - -| Field | Type | Required | Description | Example | -| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -| `number` | *OptionalNullable[str]* | :heavy_minus_sign: | A phone number. | **Example 1:** +44 25691 154789
**Example 2:** (877) 492-8687
**Example 3:** 01224 658 999 | +# PhoneNumberItems + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | +| `number` | *OptionalNullable[str]* | :heavy_minus_sign: | A phone number. | **Example 1:** +44 25691 154789
**Example 2:** (877) 492-8687
**Example 3:** 01224 658 999 | | `type` | [shared.Type](../../models/shared/type.md) | :heavy_check_mark: | The type of phone number | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/phonenumberitemstype.md b/sync-for-expenses/docs/models/shared/phonenumberitemstype.md new file mode 100644 index 000000000..f147f44f9 --- /dev/null +++ b/sync-for-expenses/docs/models/shared/phonenumberitemstype.md @@ -0,0 +1,20 @@ +# PhoneNumberItemsType + +## Example Usage + +```python +from codat_sync_for_expenses.models.shared import PhoneNumberItemsType + +value = PhoneNumberItemsType.PRIMARY +``` + + +## Values + +| Name | Value | +| ---------- | ---------- | +| `PRIMARY` | Primary | +| `LANDLINE` | Landline | +| `MOBILE` | Mobile | +| `FAX` | Fax | +| `UNKNOWN` | Unknown | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/pulloperation.md b/sync-for-expenses/docs/models/shared/pulloperation.md index bea7bb1d5..8a2742f20 100644 --- a/sync-for-expenses/docs/models/shared/pulloperation.md +++ b/sync-for-expenses/docs/models/shared/pulloperation.md @@ -1,22 +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` | *OptionalNullable[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` | [shared.DatasetStatus](../../models/shared/datasetstatus.md) | :heavy_check_mark: | The current status of the dataset. | | -| `status_description` | *OptionalNullable[str]* | :heavy_minus_sign: | Additional information about the dataset status. | Paused until 2022-10-23T00:00:00.000Z | \ No newline at end of file +# 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: | Date of the transfer transaction as recorded in the accounting software. | | +| `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` | *OptionalNullable[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: | Date of the transfer transaction as recorded in the accounting software. | | +| `status` | [shared.DatasetStatus](../../models/shared/datasetstatus.md) | :heavy_check_mark: | The current status of the dataset. | | +| `status_description` | *OptionalNullable[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-expenses/docs/models/shared/pulloperations.md b/sync-for-expenses/docs/models/shared/pulloperations.md index a5761e0aa..1c994a999 100644 --- a/sync-for-expenses/docs/models/shared/pulloperations.md +++ b/sync-for-expenses/docs/models/shared/pulloperations.md @@ -1,12 +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 | | +# 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-expenses/docs/models/shared/pushchangetype.md b/sync-for-expenses/docs/models/shared/pushchangetype.md index 9eb2c36e8..49eb7ef6e 100644 --- a/sync-for-expenses/docs/models/shared/pushchangetype.md +++ b/sync-for-expenses/docs/models/shared/pushchangetype.md @@ -1,22 +1,22 @@ -# PushChangeType - -Type of change being applied to record in third party platform. - -## Example Usage - -```python -from codat_sync_for_expenses.models.shared import PushChangeType - -value = PushChangeType.UNKNOWN -``` - - -## Values - -| Name | Value | -| --------------------- | --------------------- | -| `UNKNOWN` | Unknown | -| `CREATED` | Created | -| `MODIFIED` | Modified | -| `DELETED` | Deleted | +# PushChangeType + +Type of change being applied to record in third party platform. + +## Example Usage + +```python +from codat_sync_for_expenses.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-expenses/docs/models/shared/pushfieldvalidation.md b/sync-for-expenses/docs/models/shared/pushfieldvalidation.md index d3558cfad..b10ead92d 100644 --- a/sync-for-expenses/docs/models/shared/pushfieldvalidation.md +++ b/sync-for-expenses/docs/models/shared/pushfieldvalidation.md @@ -1,10 +1,11 @@ -# PushFieldValidation - - -## Fields - -| Field | Type | Required | Description | -| ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | -| `details` | *str* | :heavy_check_mark: | Details on the validation issue. | -| `field` | *Optional[str]* | :heavy_minus_sign: | Field name that resulted in the validation issue. | +# PushFieldValidation + + +## Fields + +| Field | Type | Required | Description | +| ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------- | +| `additional_properties` | Dict[str, *Any*] | :heavy_check_mark: | N/A | +| `details` | *str* | :heavy_check_mark: | Details on the validation issue. | +| `field` | *Optional[str]* | :heavy_minus_sign: | Field name that resulted in the validation issue. | | `ref` | *OptionalNullable[str]* | :heavy_minus_sign: | Unique reference identifier for the validation issue. | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/pushoperation.md b/sync-for-expenses/docs/models/shared/pushoperation.md index d01e17840..bd39cb20d 100644 --- a/sync-for-expenses/docs/models/shared/pushoperation.md +++ b/sync-for-expenses/docs/models/shared/pushoperation.md @@ -1,20 +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[shared.DataType]](../../models/shared/datatype.md) | :heavy_minus_sign: | Available data types | invoices | -| `error_message` | *OptionalNullable[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` | *OptionalNullable[int]* | :heavy_minus_sign: | Number of minutes the push operation must complete within before it times out. | | -| ~~`timeout_in_seconds`~~ | *OptionalNullable[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 +# 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: | The datetime when the push was completed, null if Pending. | | +| `data_connection_key` | *str* | :heavy_check_mark: | Unique identifier for a company's data connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | +| `data_type` | [Optional[shared.DataType]](../../models/shared/datatype.md) | :heavy_minus_sign: | Available data types | invoices | +| `error_message` | *OptionalNullable[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: | The datetime when the push was requested. | | +| `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` | *OptionalNullable[int]* | :heavy_minus_sign: | Number of minutes the push operation must complete within before it times out. | | +| ~~`timeout_in_seconds`~~ | *OptionalNullable[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-expenses/docs/models/shared/pushoperationchange.md b/sync-for-expenses/docs/models/shared/pushoperationchange.md index d5516b5c7..ef8fa0986 100644 --- a/sync-for-expenses/docs/models/shared/pushoperationchange.md +++ b/sync-for-expenses/docs/models/shared/pushoperationchange.md @@ -1,10 +1,10 @@ -# PushOperationChange - - -## Fields - -| Field | Type | Required | Description | -| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | -| `attachment_id` | *OptionalNullable[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 +# PushOperationChange + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | +| `attachment_id` | *OptionalNullable[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: | N/A | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/pushoperationref.md b/sync-for-expenses/docs/models/shared/pushoperationref.md index 7c26e1c4f..f7efa342a 100644 --- a/sync-for-expenses/docs/models/shared/pushoperationref.md +++ b/sync-for-expenses/docs/models/shared/pushoperationref.md @@ -1,9 +1,10 @@ -# PushOperationRef - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | -| `data_type` | [Optional[shared.DataType]](../../models/shared/datatype.md) | :heavy_minus_sign: | Available data types | invoices | -| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for a push operation. | | \ No newline at end of file +# PushOperationRef + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | +| `additional_properties` | Dict[str, *Any*] | :heavy_check_mark: | N/A | +| `data_type` | [Optional[shared.DataType]](../../models/shared/datatype.md) | :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-expenses/docs/models/shared/pushoperations.md b/sync-for-expenses/docs/models/shared/pushoperations.md index 6a06b9c2b..776ac813c 100644 --- a/sync-for-expenses/docs/models/shared/pushoperations.md +++ b/sync-for-expenses/docs/models/shared/pushoperations.md @@ -1,12 +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 | | +# 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-expenses/docs/models/shared/pushoperationstatus.md b/sync-for-expenses/docs/models/shared/pushoperationstatus.md index e04e39490..2d52d6738 100644 --- a/sync-for-expenses/docs/models/shared/pushoperationstatus.md +++ b/sync-for-expenses/docs/models/shared/pushoperationstatus.md @@ -1,21 +1,21 @@ -# PushOperationStatus - -The current status of the push operation. - -## Example Usage - -```python -from codat_sync_for_expenses.models.shared import PushOperationStatus - -value = PushOperationStatus.PENDING -``` - - -## Values - -| Name | Value | -| ----------- | ----------- | -| `PENDING` | Pending | -| `FAILED` | Failed | -| `SUCCESS` | Success | +# PushOperationStatus + +The current status of the push operation. + +## Example Usage + +```python +from codat_sync_for_expenses.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-expenses/docs/models/shared/pushoption.md b/sync-for-expenses/docs/models/shared/pushoption.md index e908d0b28..9bff99cd3 100644 --- a/sync-for-expenses/docs/models/shared/pushoption.md +++ b/sync-for-expenses/docs/models/shared/pushoption.md @@ -1,14 +1,14 @@ -# PushOption - - -## Fields - -| Field | Type | Required | Description | -| --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | -| `description` | *Optional[str]* | :heavy_minus_sign: | A description of the property. | -| `display_name` | *str* | :heavy_check_mark: | The property's display name. | -| `options` | List[[shared.PushOptionChoice](../../models/shared/pushoptionchoice.md)] | :heavy_minus_sign: | N/A | -| `properties` | Dict[str, [shared.PushOptionProperty](../../models/shared/pushoptionproperty.md)] | :heavy_minus_sign: | N/A | -| `required` | *bool* | :heavy_check_mark: | The property is required if `True`. | -| `type` | [shared.PushOptionType](../../models/shared/pushoptiontype.md) | :heavy_check_mark: | The option type. | +# PushOption + + +## Fields + +| Field | Type | Required | Description | +| --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | +| `description` | *Optional[str]* | :heavy_minus_sign: | A description of the property. | +| `display_name` | *str* | :heavy_check_mark: | The property's display name. | +| `options` | List[[shared.PushOptionChoice](../../models/shared/pushoptionchoice.md)] | :heavy_minus_sign: | N/A | +| `properties` | Dict[str, [shared.PushOptionProperty](../../models/shared/pushoptionproperty.md)] | :heavy_minus_sign: | N/A | +| `required` | *bool* | :heavy_check_mark: | The property is required if `True`. | +| `type` | [shared.PushOptionType](../../models/shared/pushoptiontype.md) | :heavy_check_mark: | The option type. | | `validation` | [Optional[shared.PushValidationInfo]](../../models/shared/pushvalidationinfo.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/pushoptionchoice.md b/sync-for-expenses/docs/models/shared/pushoptionchoice.md index 44e988b26..8c993a020 100644 --- a/sync-for-expenses/docs/models/shared/pushoptionchoice.md +++ b/sync-for-expenses/docs/models/shared/pushoptionchoice.md @@ -1,12 +1,12 @@ -# PushOptionChoice - - -## Fields - -| Field | Type | Required | Description | -| ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | -| `description` | *Optional[str]* | :heavy_minus_sign: | A description of the property. | -| `display_name` | *Optional[str]* | :heavy_minus_sign: | The property's display name. | -| `required` | *Optional[bool]* | :heavy_minus_sign: | The property is required if `True`. | -| `type` | [Optional[shared.PushOptionType]](../../models/shared/pushoptiontype.md) | :heavy_minus_sign: | The option type. | +# PushOptionChoice + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | +| `description` | *Optional[str]* | :heavy_minus_sign: | A description of the property. | +| `display_name` | *Optional[str]* | :heavy_minus_sign: | The property's display name. | +| `required` | *Optional[bool]* | :heavy_minus_sign: | The property is required if `True`. | +| `type` | [Optional[shared.PushOptionType]](../../models/shared/pushoptiontype.md) | :heavy_minus_sign: | The option type. | | `value` | *Optional[str]* | :heavy_minus_sign: | Allowed value for field. | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/pushoptionproperty.md b/sync-for-expenses/docs/models/shared/pushoptionproperty.md index 2bedd19d3..02801135b 100644 --- a/sync-for-expenses/docs/models/shared/pushoptionproperty.md +++ b/sync-for-expenses/docs/models/shared/pushoptionproperty.md @@ -1,14 +1,14 @@ -# PushOptionProperty - - -## Fields - -| Field | Type | Required | Description | -| --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | -| `description` | *str* | :heavy_check_mark: | A description of the property. | -| `display_name` | *str* | :heavy_check_mark: | The property's display name. | -| `options` | List[[shared.PushOptionChoice](../../models/shared/pushoptionchoice.md)] | :heavy_minus_sign: | N/A | -| `properties` | Dict[str, [shared.PushOptionProperty](../../models/shared/pushoptionproperty.md)] | :heavy_minus_sign: | N/A | -| `required` | *bool* | :heavy_check_mark: | The property is required if `True`. | -| `type` | [shared.PushOptionType](../../models/shared/pushoptiontype.md) | :heavy_check_mark: | The option type. | +# PushOptionProperty + + +## Fields + +| Field | Type | Required | Description | +| --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | +| `description` | *str* | :heavy_check_mark: | A description of the property. | +| `display_name` | *str* | :heavy_check_mark: | The property's display name. | +| `options` | List[[shared.PushOptionChoice](../../models/shared/pushoptionchoice.md)] | :heavy_minus_sign: | N/A | +| `properties` | Dict[str, [shared.PushOptionProperty](../../models/shared/pushoptionproperty.md)] | :heavy_minus_sign: | N/A | +| `required` | *bool* | :heavy_check_mark: | The property is required if `True`. | +| `type` | [shared.PushOptionType](../../models/shared/pushoptiontype.md) | :heavy_check_mark: | The option type. | | `validation` | [Optional[shared.PushValidationInfo]](../../models/shared/pushvalidationinfo.md) | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/pushoptiontype.md b/sync-for-expenses/docs/models/shared/pushoptiontype.md index c5c9f39da..b3160dd71 100644 --- a/sync-for-expenses/docs/models/shared/pushoptiontype.md +++ b/sync-for-expenses/docs/models/shared/pushoptiontype.md @@ -1,25 +1,23 @@ -# PushOptionType - -The option type. - -## Example Usage - -```python -from codat_sync_for_expenses.models.shared import PushOptionType - -value = PushOptionType.ARRAY -``` - - -## Values - -| Name | Value | -| ------------ | ------------ | -| `ARRAY` | Array | -| `OBJECT` | Object | -| `STRING` | String | -| `NUMBER` | Number | -| `BOOLEAN` | Boolean | -| `DATE_TIME` | DateTime | -| `FILE` | File | +# PushOptionType + +## Example Usage + +```python +from codat_sync_for_expenses.models.shared import PushOptionType + +value = PushOptionType.ARRAY +``` + + +## Values + +| Name | Value | +| ------------ | ------------ | +| `ARRAY` | Array | +| `OBJECT` | Object | +| `STRING` | String | +| `NUMBER` | Number | +| `BOOLEAN` | Boolean | +| `DATE_TIME` | DateTime | +| `FILE` | File | | `MULTI_PART` | MultiPart | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/pushvalidationinfo.md b/sync-for-expenses/docs/models/shared/pushvalidationinfo.md index 110eb3f76..ad9013935 100644 --- a/sync-for-expenses/docs/models/shared/pushvalidationinfo.md +++ b/sync-for-expenses/docs/models/shared/pushvalidationinfo.md @@ -1,9 +1,10 @@ -# PushValidationInfo - - -## Fields - -| Field | Type | Required | Description | -| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | -| `information` | List[[shared.PushFieldValidation](../../models/shared/pushfieldvalidation.md)] | :heavy_minus_sign: | N/A | +# PushValidationInfo + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | +| `additional_properties` | Dict[str, *Any*] | :heavy_check_mark: | N/A | +| `information` | List[[shared.PushFieldValidation](../../models/shared/pushfieldvalidation.md)] | :heavy_minus_sign: | N/A | | `warnings` | List[[shared.PushFieldValidation](../../models/shared/pushfieldvalidation.md)] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/recordref.md b/sync-for-expenses/docs/models/shared/recordref.md index cd4ef66cc..205ff3333 100644 --- a/sync-for-expenses/docs/models/shared/recordref.md +++ b/sync-for-expenses/docs/models/shared/recordref.md @@ -1,8 +1,8 @@ -# RecordRef - - -## Fields - -| Field | Type | Required | Description | Example | -| ---------------------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------- | +# RecordRef + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------- | | `id` | *Optional[str]* | :heavy_minus_sign: | Identifier of linked reference from mapping options. | 40e3e57c-2322-4898-966c-ca41adfd23fd | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/reimbursableexpensetransaction.md b/sync-for-expenses/docs/models/shared/reimbursableexpensetransaction.md index 39f21606e..cb0564f46 100644 --- a/sync-for-expenses/docs/models/shared/reimbursableexpensetransaction.md +++ b/sync-for-expenses/docs/models/shared/reimbursableexpensetransaction.md @@ -1,17 +1,17 @@ -# ReimbursableExpenseTransaction - - -## Fields - -| Field | Type | Required | Description | Example | -| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `ap_account_ref` | [OptionalNullable[shared.ApAccountRef]](../../models/shared/apaccountref.md) | :heavy_minus_sign: | N/A | | -| `contact_ref` | [shared.ReimbursementContactRef](../../models/shared/reimbursementcontactref.md) | :heavy_check_mark: | N/A | | -| `currency` | *str* | :heavy_check_mark: | Currency the transaction was recorded in. | GBP | -| `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: | 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` | *str* | :heavy_check_mark: | Your unique identifier for the transaction. | 4d7c6929-7770-412b-91bb-44d3bc71d111 | -| `issue_date` | *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 | -| `lines` | List[[shared.ReimbursableExpenseTransactionLine](../../models/shared/reimbursableexpensetransactionline.md)] | :heavy_minus_sign: | Array of transaction lines. | | -| `notes` | *Optional[str]* | :heavy_minus_sign: | Any private, company notes about the transaction. | APPLE.COM/BILL - 09001077498 - Card Ending: 4590 | +# ReimbursableExpenseTransaction + + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `ap_account_ref` | [OptionalNullable[shared.ApAccountRef]](../../models/shared/apaccountref.md) | :heavy_minus_sign: | N/A | | +| `contact_ref` | [shared.ReimbursementContactRef](../../models/shared/reimbursementcontactref.md) | :heavy_check_mark: | N/A | | +| `currency` | *str* | :heavy_check_mark: | Currency the transaction was recorded in. | GBP | +| `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. | | +| `id` | *str* | :heavy_check_mark: | Your unique identifier for the transaction. | 4d7c6929-7770-412b-91bb-44d3bc71d111 | +| `issue_date` | *str* | :heavy_check_mark: | Date of the transaction was recorded. | | +| `lines` | List[[shared.ReimbursableExpenseTransactionLine](../../models/shared/reimbursableexpensetransactionline.md)] | :heavy_minus_sign: | Array of transaction lines. | | +| `notes` | *Optional[str]* | :heavy_minus_sign: | Any private, company notes about the transaction. | APPLE.COM/BILL - 09001077498 - Card Ending: 4590 | | `reference` | *OptionalNullable[str]* | :heavy_minus_sign: | User-friendly reference for the reimbursable expense. | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/reimbursableexpensetransactionline.md b/sync-for-expenses/docs/models/shared/reimbursableexpensetransactionline.md index 3b7c4f24d..25e207944 100644 --- a/sync-for-expenses/docs/models/shared/reimbursableexpensetransactionline.md +++ b/sync-for-expenses/docs/models/shared/reimbursableexpensetransactionline.md @@ -1,15 +1,15 @@ -# ReimbursableExpenseTransactionLine - - -## Fields - -| Field | Type | Required | Description | Example | -| --------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `account_ref` | [Optional[shared.RecordRef]](../../models/shared/recordref.md) | :heavy_minus_sign: | N/A | | -| `description` | *Optional[str]* | :heavy_minus_sign: | line description | 2-night hotel stay | -| `invoice_to` | [OptionalNullable[shared.InvoiceTo]](../../models/shared/invoiceto.md) | :heavy_minus_sign: | Unique identifier for the customer billed for the transaction. The `invoiceTo` object is currently supported only for QuickBooks Online and QuickBooks Desktop. | | -| `item_ref` | [OptionalNullable[shared.ItemRef]](../../models/shared/itemref.md) | :heavy_minus_sign: | N/A | | -| `net_amount` | *Decimal* | :heavy_check_mark: | Amount of the line, exclusive of tax. | 100 | -| `tax_amount` | *Optional[Decimal]* | :heavy_minus_sign: | Amount of tax for the line. | 20 | -| `tax_rate_ref` | [Optional[shared.RecordRef]](../../models/shared/recordref.md) | :heavy_minus_sign: | N/A | | -| `tracking_refs` | List[[shared.TrackingRef](../../models/shared/trackingref.md)] | :heavy_minus_sign: | N/A | | \ No newline at end of file +# ReimbursableExpenseTransactionLine + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `account_ref` | [Optional[shared.RecordRef]](../../models/shared/recordref.md) | :heavy_minus_sign: | The `accountRef` contains the `id` of the account the transaction is against. The `accountRef` object is required for all integrations except QBD which currently supports either itemRef or accountRef. | | +| `description` | *Optional[str]* | :heavy_minus_sign: | line description | 2-night hotel stay | +| `invoice_to` | [OptionalNullable[shared.InvoiceTo]](../../models/shared/invoiceto.md) | :heavy_minus_sign: | Unique identifier for the customer billed for the transaction. The `invoiceTo` object is currently supported only for QuickBooks Online and QuickBooks Desktop. | | +| `item_ref` | [OptionalNullable[shared.ItemRef]](../../models/shared/itemref.md) | :heavy_minus_sign: | N/A | | +| `net_amount` | *Decimal* | :heavy_check_mark: | Amount of the line, exclusive of tax. | 100 | +| `tax_amount` | *Optional[Decimal]* | :heavy_minus_sign: | Amount of tax for the line. | 20 | +| `tax_rate_ref` | [Optional[shared.RecordRef]](../../models/shared/recordref.md) | :heavy_minus_sign: | N/A | | +| `tracking_refs` | List[[shared.TrackingRef](../../models/shared/trackingref.md)] | :heavy_minus_sign: | N/A | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/reimbursementcontactref.md b/sync-for-expenses/docs/models/shared/reimbursementcontactref.md index bb509541f..4f2fc1a0e 100644 --- a/sync-for-expenses/docs/models/shared/reimbursementcontactref.md +++ b/sync-for-expenses/docs/models/shared/reimbursementcontactref.md @@ -1,8 +1,8 @@ -# ReimbursementContactRef - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +# ReimbursementContactRef + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | | `id` | *str* | :heavy_check_mark: | Identifier of contact. | 40e3e57c-2322-4898-966c-ca41adfd23fd | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/schemadatatype.md b/sync-for-expenses/docs/models/shared/schemadatatype.md index 39865d9ab..eb34b5c60 100644 --- a/sync-for-expenses/docs/models/shared/schemadatatype.md +++ b/sync-for-expenses/docs/models/shared/schemadatatype.md @@ -1,60 +1,60 @@ -# SchemaDataType - -Available data types - -## Example Usage - -```python -from codat_sync_for_expenses.models.shared import SchemaDataType - -value = SchemaDataType.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 | +# SchemaDataType + +Available data types + +## Example Usage + +```python +from codat_sync_for_expenses.models.shared import SchemaDataType + +value = SchemaDataType.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-expenses/docs/models/shared/schematransaction.md b/sync-for-expenses/docs/models/shared/schematransaction.md index 63efd2454..b2f651cfb 100644 --- a/sync-for-expenses/docs/models/shared/schematransaction.md +++ b/sync-for-expenses/docs/models/shared/schematransaction.md @@ -1,11 +1,12 @@ -# SchemaTransaction - - -## Fields - -| Field | Type | Required | Description | Example | -| ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | -| `integration_type` | [OptionalNullable[shared.IntegrationType]](../../models/shared/integrationtype.md) | :heavy_minus_sign: | Type of transaction that has been processed e.g. Expense or Bank Feed. | expenses | -| `message` | *OptionalNullable[str]* | :heavy_minus_sign: | Metadata such as validation errors or the resulting record created in the accounting software. | | -| `status` | [OptionalNullable[shared.TransactionStatus]](../../models/shared/transactionstatus.md) | :heavy_minus_sign: | Status of the transaction. | Completed | +# SchemaTransaction + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | +| `additional_properties` | Dict[str, *Any*] | :heavy_check_mark: | N/A | | +| `integration_type` | [Optional[shared.IntegrationType]](../../models/shared/integrationtype.md) | :heavy_minus_sign: | Type of transaction that has been processed e.g. Expense or Bank Feed. | expenses | +| `message` | *OptionalNullable[str]* | :heavy_minus_sign: | Metadata such as validation errors or the resulting record created in the accounting software. | | +| `status` | [OptionalNullable[shared.TransactionStatus]](../../models/shared/transactionstatus.md) | :heavy_minus_sign: | Status of the transaction. | Completed | | `transaction_id` | *OptionalNullable[str]* | :heavy_minus_sign: | Your unique idenfier of the transaction. | aa02271d-ed5f-47f5-be76-778d5905225a | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/security.md b/sync-for-expenses/docs/models/shared/security.md index 2b68bd0e7..e7a8e4384 100644 --- a/sync-for-expenses/docs/models/shared/security.md +++ b/sync-for-expenses/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-expenses/docs/models/shared/sourcetype.md b/sync-for-expenses/docs/models/shared/sourcetype.md index 2aa214f61..85c58fc93 100644 --- a/sync-for-expenses/docs/models/shared/sourcetype.md +++ b/sync-for-expenses/docs/models/shared/sourcetype.md @@ -1,24 +1,24 @@ -# SourceType - -The type of platform of the connection. - -## Example Usage - -```python -from codat_sync_for_expenses.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_expenses.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-expenses/docs/models/shared/status.md b/sync-for-expenses/docs/models/shared/status.md index 33ac01645..137eca2e7 100644 --- a/sync-for-expenses/docs/models/shared/status.md +++ b/sync-for-expenses/docs/models/shared/status.md @@ -1,38 +1,36 @@ -# Status - -The current status of the dataset. - -## Example Usage - -```python -from codat_sync_for_expenses.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 | +# Status + +## Example Usage + +```python +from codat_sync_for_expenses.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-expenses/docs/models/shared/supplementaldata.md b/sync-for-expenses/docs/models/shared/supplementaldata.md index 7415a8519..b0c0c829e 100644 --- a/sync-for-expenses/docs/models/shared/supplementaldata.md +++ b/sync-for-expenses/docs/models/shared/supplementaldata.md @@ -1,12 +1,12 @@ -# SupplementalData - -Supplemental data is additional data you can include in our standard data types. - -It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. - - -## Fields - -| Field | Type | Required | Description | -| --------------------------- | --------------------------- | --------------------------- | --------------------------- | -| `content` | Dict[str, Dict[str, *Any*]] | :heavy_minus_sign: | N/A | \ No newline at end of file +# SupplementalData + +Supplemental data is additional data you can include in our standard data types. + +It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. + + +## Fields + +| Field | Type | Required | Description | +| --------------------------- | --------------------------- | --------------------------- | --------------------------- | +| `content` | Dict[str, *Dict[str, Any]*] | :heavy_minus_sign: | N/A | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/supplier.md b/sync-for-expenses/docs/models/shared/supplier.md index 3d1c0b2bf..226680687 100644 --- a/sync-for-expenses/docs/models/shared/supplier.md +++ b/sync-for-expenses/docs/models/shared/supplier.md @@ -1,25 +1,25 @@ -# Supplier - -## Overview - -From the **Suppliers** endpoints, you can retrieve a list of [all the suppliers for a company](https://docs.codat.io/sync-for-expenses-api#/operations/list-suppliers). Suppliers' data links to accounts payable [bills](https://docs.codat.io/sync-for-expenses-api#/schemas/Bill). - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `addresses` | List[[shared.Items](../../models/shared/items.md)] | :heavy_minus_sign: | An array of Addresses. | | -| `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. | | -| `metadata` | [Optional[shared.Metadata]](../../models/shared/metadata.md) | :heavy_minus_sign: | N/A | | -| `modified_date` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `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 | -| `registration_number` | *OptionalNullable[str]* | :heavy_minus_sign: | Company number of the supplier. In the UK, this is typically the company registration number issued by Companies House. | | -| `source_modified_date` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `status` | [shared.SupplierStatus](../../models/shared/supplierstatus.md) | :heavy_check_mark: | Status of the supplier. | | -| `supplemental_data` | [Optional[shared.SupplementalData]](../../models/shared/supplementaldata.md) | :heavy_minus_sign: | Supplemental data is additional data you can include in our standard data types.

It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. | | -| `supplier_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the supplier as recorded in the accounting system, typically the company name. | | +# Supplier + +## Overview + +From the **Suppliers** endpoints, you can retrieve a list of [all the suppliers for a company](https://docs.codat.io/sync-for-expenses-api#/operations/list-suppliers). Suppliers' data links to accounts payable [bills](https://docs.codat.io/sync-for-expenses-api#/schemas/Bill). + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `addresses` | List[[shared.Items](../../models/shared/items.md)] | :heavy_minus_sign: | An array of Addresses. | | +| `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. | | +| `metadata` | [Optional[shared.Metadata]](../../models/shared/metadata.md) | :heavy_minus_sign: | N/A | | +| `modified_date` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `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 | +| `registration_number` | *OptionalNullable[str]* | :heavy_minus_sign: | Company number of the supplier. In the UK, this is typically the company registration number issued by Companies House. | | +| `source_modified_date` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | +| `status` | [shared.SupplierStatus](../../models/shared/supplierstatus.md) | :heavy_check_mark: | Status of the supplier. | | +| `supplemental_data` | [Optional[shared.SupplementalData]](../../models/shared/supplementaldata.md) | :heavy_minus_sign: | Supplemental data is additional data you can include in our standard data types.

It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. | | +| `supplier_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the supplier as recorded in the accounting system, typically the company name. | | | `tax_number` | *OptionalNullable[str]* | :heavy_minus_sign: | Supplier's company tax number. | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/supplierdetails.md b/sync-for-expenses/docs/models/shared/supplierdetails.md index fe67734d8..fd4c2d543 100644 --- a/sync-for-expenses/docs/models/shared/supplierdetails.md +++ b/sync-for-expenses/docs/models/shared/supplierdetails.md @@ -1,8 +1,8 @@ -# SupplierDetails - - -## Fields - -| Field | Type | Required | Description | -| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | +# SupplierDetails + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | | `id` | *Optional[str]* | :heavy_minus_sign: | Identifier for the supplier, unique to the company in the accounting software. | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/suppliers.md b/sync-for-expenses/docs/models/shared/suppliers.md index bb6880b0d..c5173366e 100644 --- a/sync-for-expenses/docs/models/shared/suppliers.md +++ b/sync-for-expenses/docs/models/shared/suppliers.md @@ -1,12 +1,12 @@ -# Suppliers - - -## 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[[Nullable[shared.Supplier]](../../models/shared/supplier.md)] | :heavy_minus_sign: | N/A | | +# Suppliers + + +## 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[[Nullable[shared.Supplier]](../../models/shared/supplier.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-expenses/docs/models/shared/supplierstatus.md b/sync-for-expenses/docs/models/shared/supplierstatus.md index 60d0de4fb..b47ab26f3 100644 --- a/sync-for-expenses/docs/models/shared/supplierstatus.md +++ b/sync-for-expenses/docs/models/shared/supplierstatus.md @@ -1,20 +1,18 @@ -# SupplierStatus - -Status of the supplier. - -## Example Usage - -```python -from codat_sync_for_expenses.models.shared import SupplierStatus - -value = SupplierStatus.UNKNOWN -``` - - -## Values - -| Name | Value | -| ---------- | ---------- | -| `UNKNOWN` | Unknown | -| `ACTIVE` | Active | +# SupplierStatus + +## Example Usage + +```python +from codat_sync_for_expenses.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-expenses/docs/models/shared/synccompletewebhook.md b/sync-for-expenses/docs/models/shared/synccompletewebhook.md new file mode 100644 index 000000000..fe2992b08 --- /dev/null +++ b/sync-for-expenses/docs/models/shared/synccompletewebhook.md @@ -0,0 +1,17 @@ +# SyncCompleteWebhook + +Webhook request body used to notify that a sync has completed. + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `alert_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of the webhook event. | | +| `client_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for your client in Codat. | | +| `client_name` | *Optional[str]* | :heavy_minus_sign: | Name of your client in Codat. | | +| `company_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for your SMB in Codat. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `data` | [Optional[shared.SyncCompleteWebhookData]](../../models/shared/synccompletewebhookdata.md) | :heavy_minus_sign: | N/A | | +| `message` | *Optional[str]* | :heavy_minus_sign: | A human-readable message about the webhook. | | +| ~~`rule_id`~~ | *Optional[str]* | :heavy_minus_sign: | : warning: ** DEPRECATED **: This will be removed in a future release, please migrate away from it as soon as possible.

Unique identifier for the rule. | | +| `rule_type` | *Optional[str]* | :heavy_minus_sign: | The type of rule. | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/synccompletewebhookdata.md b/sync-for-expenses/docs/models/shared/synccompletewebhookdata.md new file mode 100644 index 000000000..7c8dfb102 --- /dev/null +++ b/sync-for-expenses/docs/models/shared/synccompletewebhookdata.md @@ -0,0 +1,9 @@ +# SyncCompleteWebhookData + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------- | -------------------------------------- | -------------------------------------- | -------------------------------------- | -------------------------------------- | +| `sync_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for the failed sync. | a9367074-b5c3-42c4-9be4-be129f43577e | +| `sync_type` | *Optional[str]* | :heavy_minus_sign: | The type of sync being performed. | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/syncfailedwebhook.md b/sync-for-expenses/docs/models/shared/syncfailedwebhook.md new file mode 100644 index 000000000..4b5f440b5 --- /dev/null +++ b/sync-for-expenses/docs/models/shared/syncfailedwebhook.md @@ -0,0 +1,17 @@ +# SyncFailedWebhook + +Webhook request body used to notify that a sync has failed. + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `alert_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of the webhook event. | | +| `client_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for your client in Codat. | | +| `client_name` | *Optional[str]* | :heavy_minus_sign: | Name of your client in Codat. | | +| `company_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for your SMB in Codat. | 8a210b68-6988-11ed-a1eb-0242ac120002 | +| `data` | [Optional[shared.SyncFailedWebhookData]](../../models/shared/syncfailedwebhookdata.md) | :heavy_minus_sign: | N/A | | +| `message` | *Optional[str]* | :heavy_minus_sign: | A human-readable message about the webhook. | | +| ~~`rule_id`~~ | *Optional[str]* | :heavy_minus_sign: | : warning: ** DEPRECATED **: This will be removed in a future release, please migrate away from it as soon as possible.

Unique identifier for the rule. | | +| `rule_type` | *Optional[str]* | :heavy_minus_sign: | The type of rule. | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/syncfailedwebhookdata.md b/sync-for-expenses/docs/models/shared/syncfailedwebhookdata.md new file mode 100644 index 000000000..d3a38842c --- /dev/null +++ b/sync-for-expenses/docs/models/shared/syncfailedwebhookdata.md @@ -0,0 +1,10 @@ +# SyncFailedWebhookData + + +## Fields + +| Field | Type | Required | Description | Example | +| -------------------------------------- | -------------------------------------- | -------------------------------------- | -------------------------------------- | -------------------------------------- | +| `failure_stage` | *Optional[str]* | :heavy_minus_sign: | The stage of the job the sync failed. | | +| `sync_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for the failed sync. | a9367074-b5c3-42c4-9be4-be129f43577e | +| `sync_type` | *Optional[str]* | :heavy_minus_sign: | The type of sync being performed. | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/syncinitiated.md b/sync-for-expenses/docs/models/shared/syncinitiated.md new file mode 100644 index 000000000..cf5b80d5a --- /dev/null +++ b/sync-for-expenses/docs/models/shared/syncinitiated.md @@ -0,0 +1,9 @@ +# SyncInitiated + + +## Fields + +| Field | Type | Required | Description | +| ----------------------------------------- | ----------------------------------------- | ----------------------------------------- | ----------------------------------------- | +| `additional_properties` | Dict[str, *Any*] | :heavy_check_mark: | N/A | +| `sync_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for the sync initiated. | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/taxratemappinginfo.md b/sync-for-expenses/docs/models/shared/taxratemappinginfo.md index edb55bd02..db219c0fe 100644 --- a/sync-for-expenses/docs/models/shared/taxratemappinginfo.md +++ b/sync-for-expenses/docs/models/shared/taxratemappinginfo.md @@ -1,13 +1,14 @@ -# TaxRateMappingInfo - - -## Fields - -| Field | Type | Required | Description | Example | -| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | -| `code` | *OptionalNullable[str]* | :heavy_minus_sign: | Code for the tax rate from the accounting software. | 20% Bill tax | -| `effective_tax_rate` | *Optional[Decimal]* | :heavy_minus_sign: | Effective tax rate. | 20 | -| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of tax rate. | 23_Bills | -| `name` | *Optional[str]* | :heavy_minus_sign: | Name of the tax rate in the accounting software. | 20% Bill tax Bills | -| `total_tax_rate` | *Optional[Decimal]* | :heavy_minus_sign: | Total (not compounded) sum of the components of a tax rate. | 20 | +# TaxRateMappingInfo + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | +| `additional_properties` | Dict[str, *Any*] | :heavy_check_mark: | N/A | | +| `code` | *OptionalNullable[str]* | :heavy_minus_sign: | Code for the tax rate from the accounting software. | 20% Bill tax | +| `effective_tax_rate` | *Optional[Decimal]* | :heavy_minus_sign: | Effective tax rate. | 20 | +| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of tax rate. | 23_Bills | +| `name` | *Optional[str]* | :heavy_minus_sign: | Name of the tax rate in the accounting software. | 20% Bill tax Bills | +| `total_tax_rate` | *Optional[Decimal]* | :heavy_minus_sign: | Total (not compounded) sum of the components of a tax rate. | 20 | | `valid_transaction_types` | List[[shared.ValidTransactionTypes](../../models/shared/validtransactiontypes.md)] | :heavy_minus_sign: | Supported transaction types for the account. | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/to.md b/sync-for-expenses/docs/models/shared/to.md deleted file mode 100644 index 9e32f98f0..000000000 --- a/sync-for-expenses/docs/models/shared/to.md +++ /dev/null @@ -1,9 +0,0 @@ -# To - - -## Fields - -| Field | Type | Required | Description | -| ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | -| `account_ref` | [shared.TransferTransactionRequestAccountReference](../../models/shared/transfertransactionrequestaccountreference.md) | :heavy_check_mark: | Reference of the account you are transferring money to. | -| `amount` | *Decimal* | :heavy_check_mark: | Amount that has been transferred to the account in the native currency of the account. | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/trackingcategorymappinginfo.md b/sync-for-expenses/docs/models/shared/trackingcategorymappinginfo.md index 86fe420f0..7d32e5b16 100644 --- a/sync-for-expenses/docs/models/shared/trackingcategorymappinginfo.md +++ b/sync-for-expenses/docs/models/shared/trackingcategorymappinginfo.md @@ -1,11 +1,12 @@ -# TrackingCategoryMappingInfo - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------------- | ----------------------------------------------------------------------- | ----------------------------------------------------------------------- | ----------------------------------------------------------------------- | ----------------------------------------------------------------------- | -| `has_children` | *Optional[bool]* | :heavy_minus_sign: | Boolean of whether the tracking category has child categories. | | -| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of the tracking category. | DEPARTMENT_2 | -| `name` | *Optional[str]* | :heavy_minus_sign: | Name of the tracking category as it appears in the accounting software. | New York | +# TrackingCategoryMappingInfo + + +## Fields + +| Field | Type | Required | Description | Example | +| ----------------------------------------------------------------------- | ----------------------------------------------------------------------- | ----------------------------------------------------------------------- | ----------------------------------------------------------------------- | ----------------------------------------------------------------------- | +| `additional_properties` | Dict[str, *Any*] | :heavy_check_mark: | N/A | | +| `has_children` | *Optional[bool]* | :heavy_minus_sign: | Boolean of whether the tracking category has child categories. | | +| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of the tracking category. | DEPARTMENT_2 | +| `name` | *Optional[str]* | :heavy_minus_sign: | Name of the tracking category as it appears in the accounting software. | New York | | `parent_id` | *OptionalNullable[str]* | :heavy_minus_sign: | ID of the parent tracking category | DEPARTMENTS | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/trackingref.md b/sync-for-expenses/docs/models/shared/trackingref.md index 3ca9e0262..ec6017f9a 100644 --- a/sync-for-expenses/docs/models/shared/trackingref.md +++ b/sync-for-expenses/docs/models/shared/trackingref.md @@ -1,9 +1,9 @@ -# TrackingRef - - -## Fields - -| Field | Type | Required | Description | Example | -| --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | -| `data_type` | [Optional[shared.TrackingRefDataType]](../../models/shared/trackingrefdatatype.md) | :heavy_minus_sign: | The type of the linked reference | trackingCategories | +# TrackingRef + + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | +| `data_type` | [Optional[shared.TrackingRefDataType]](../../models/shared/trackingrefdatatype.md) | :heavy_minus_sign: | The type of the linked reference | trackingCategories | | `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of the linked reference from mapping options or the unique identifier of the linked customer. | e9a1b63d-9ff0-40e7-8038-016354b987e6 | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/trackingrefadjustmenttransaction.md b/sync-for-expenses/docs/models/shared/trackingrefadjustmenttransaction.md index bd5ddd3f7..9d75373fb 100644 --- a/sync-for-expenses/docs/models/shared/trackingrefadjustmenttransaction.md +++ b/sync-for-expenses/docs/models/shared/trackingrefadjustmenttransaction.md @@ -1,9 +1,9 @@ -# TrackingRefAdjustmentTransaction - - -## Fields - -| Field | Type | Required | Description | Example | -| ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | -| `data_type` | [Optional[shared.TrackingRefAdjustmentTransactionDataType]](../../models/shared/trackingrefadjustmenttransactiondatatype.md) | :heavy_minus_sign: | The type of the linked reference | trackingCategories | +# TrackingRefAdjustmentTransaction + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | +| `data_type` | [Optional[shared.TrackingRefAdjustmentTransactionDataType]](../../models/shared/trackingrefadjustmenttransactiondatatype.md) | :heavy_minus_sign: | The type of the linked reference | trackingCategories | | `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of the linked reference from mapping options or the unique identifier of the linked customer or supplier. | e9a1b63d-9ff0-40e7-8038-016354b987e6 | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/trackingrefadjustmenttransactiondatatype.md b/sync-for-expenses/docs/models/shared/trackingrefadjustmenttransactiondatatype.md index 32d5fb830..c36de98eb 100644 --- a/sync-for-expenses/docs/models/shared/trackingrefadjustmenttransactiondatatype.md +++ b/sync-for-expenses/docs/models/shared/trackingrefadjustmenttransactiondatatype.md @@ -1,20 +1,18 @@ -# TrackingRefAdjustmentTransactionDataType - -The type of the linked reference - -## Example Usage - -```python -from codat_sync_for_expenses.models.shared import TrackingRefAdjustmentTransactionDataType - -value = TrackingRefAdjustmentTransactionDataType.TRACKING_CATEGORIES -``` - - -## Values - -| Name | Value | -| --------------------- | --------------------- | -| `TRACKING_CATEGORIES` | trackingCategories | -| `CUSTOMERS` | customers | +# TrackingRefAdjustmentTransactionDataType + +## Example Usage + +```python +from codat_sync_for_expenses.models.shared import TrackingRefAdjustmentTransactionDataType + +value = TrackingRefAdjustmentTransactionDataType.TRACKING_CATEGORIES +``` + + +## Values + +| Name | Value | +| --------------------- | --------------------- | +| `TRACKING_CATEGORIES` | trackingCategories | +| `CUSTOMERS` | customers | | `SUPPLIERS` | suppliers | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/trackingrefdatatype.md b/sync-for-expenses/docs/models/shared/trackingrefdatatype.md index befe27dae..efdf03a55 100644 --- a/sync-for-expenses/docs/models/shared/trackingrefdatatype.md +++ b/sync-for-expenses/docs/models/shared/trackingrefdatatype.md @@ -1,19 +1,17 @@ -# TrackingRefDataType - -The type of the linked reference - -## Example Usage - -```python -from codat_sync_for_expenses.models.shared import TrackingRefDataType - -value = TrackingRefDataType.TRACKING_CATEGORIES -``` - - -## Values - -| Name | Value | -| --------------------- | --------------------- | -| `TRACKING_CATEGORIES` | trackingCategories | +# TrackingRefDataType + +## Example Usage + +```python +from codat_sync_for_expenses.models.shared import TrackingRefDataType + +value = TrackingRefDataType.TRACKING_CATEGORIES +``` + + +## Values + +| Name | Value | +| --------------------- | --------------------- | +| `TRACKING_CATEGORIES` | trackingCategories | | `CUSTOMERS` | customers | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/transaction.md b/sync-for-expenses/docs/models/shared/transaction.md index 07593a6e5..8937f72a0 100644 --- a/sync-for-expenses/docs/models/shared/transaction.md +++ b/sync-for-expenses/docs/models/shared/transaction.md @@ -1,10 +1,10 @@ -# Transaction - - -## Fields - -| Field | Type | Required | Description | -| ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | -| `error_message` | *OptionalNullable[str]* | :heavy_minus_sign: | Error message for failed transaction. | -| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of the transaction. | +# Transaction + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | +| `error_message` | *OptionalNullable[str]* | :heavy_minus_sign: | Error message for failed transaction. | +| `id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier of the transaction. | | `status` | [Optional[shared.TransactionDefinitionsStatus]](../../models/shared/transactiondefinitionsstatus.md) | :heavy_minus_sign: | Status of transaction. | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/transactiondefinitionsstatus.md b/sync-for-expenses/docs/models/shared/transactiondefinitionsstatus.md index 4b5ec7609..2e4d418ad 100644 --- a/sync-for-expenses/docs/models/shared/transactiondefinitionsstatus.md +++ b/sync-for-expenses/docs/models/shared/transactiondefinitionsstatus.md @@ -1,22 +1,22 @@ -# TransactionDefinitionsStatus - -Status of transaction. - -## Example Usage - -```python -from codat_sync_for_expenses.models.shared import TransactionDefinitionsStatus - -value = TransactionDefinitionsStatus.UNKNOWN -``` - - -## Values - -| Name | Value | -| ------------ | ------------ | -| `UNKNOWN` | Unknown | -| `PUSH_ERROR` | PushError | -| `COMPLETED` | Completed | -| `FAILED` | Failed | +# TransactionDefinitionsStatus + +Status of transaction. + +## Example Usage + +```python +from codat_sync_for_expenses.models.shared import TransactionDefinitionsStatus + +value = TransactionDefinitionsStatus.UNKNOWN +``` + + +## Values + +| Name | Value | +| ------------ | ------------ | +| `UNKNOWN` | Unknown | +| `PUSH_ERROR` | PushError | +| `COMPLETED` | Completed | +| `FAILED` | Failed | | `PENDING` | Pending | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/transactions.md b/sync-for-expenses/docs/models/shared/transactions.md index d1a752145..5d874745f 100644 --- a/sync-for-expenses/docs/models/shared/transactions.md +++ b/sync-for-expenses/docs/models/shared/transactions.md @@ -1,12 +1,13 @@ -# Transactions - - -## 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.SchemaTransaction](../../models/shared/schematransaction.md)] | :heavy_minus_sign: | N/A | | +# Transactions + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| `additional_properties` | Dict[str, *Any*] | :heavy_check_mark: | N/A | | +| `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.SchemaTransaction](../../models/shared/schematransaction.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-expenses/docs/models/shared/transactionstatus.md b/sync-for-expenses/docs/models/shared/transactionstatus.md index 8be5f3789..826793081 100644 --- a/sync-for-expenses/docs/models/shared/transactionstatus.md +++ b/sync-for-expenses/docs/models/shared/transactionstatus.md @@ -1,22 +1,22 @@ -# TransactionStatus - -Status of the transaction. - -## Example Usage - -```python -from codat_sync_for_expenses.models.shared import TransactionStatus - -value = TransactionStatus.UNKNOWN -``` - - -## Values - -| Name | Value | -| ------------------ | ------------------ | -| `UNKNOWN` | Unknown | -| `PENDING` | Pending | -| `VALIDATION_ERROR` | ValidationError | -| `COMPLETED` | Completed | +# TransactionStatus + +Status of the transaction. + +## Example Usage + +```python +from codat_sync_for_expenses.models.shared import TransactionStatus + +value = TransactionStatus.UNKNOWN +``` + + +## Values + +| Name | Value | +| ------------------ | ------------------ | +| `UNKNOWN` | Unknown | +| `PENDING` | Pending | +| `VALIDATION_ERROR` | ValidationError | +| `COMPLETED` | Completed | | `PUSH_ERROR` | PushError | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/transfertransactionrequest.md b/sync-for-expenses/docs/models/shared/transfertransactionrequest.md index ac0e1d51c..d5b13e401 100644 --- a/sync-for-expenses/docs/models/shared/transfertransactionrequest.md +++ b/sync-for-expenses/docs/models/shared/transfertransactionrequest.md @@ -1,11 +1,11 @@ -# TransferTransactionRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| ----------------------------------------------------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------- | -| `date_` | *str* | :heavy_check_mark: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `description` | *Optional[str]* | :heavy_minus_sign: | Any private, company notes about the transaction. | Transfer from bank account Y to bank account Z | -| `from_` | [shared.From](../../models/shared/from_.md) | :heavy_check_mark: | N/A | | -| `to` | [shared.To](../../models/shared/to.md) | :heavy_check_mark: | N/A | | \ No newline at end of file +# TransferTransactionRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | +| `date_` | *str* | :heavy_check_mark: | Date of the transfer transaction as recorded in the accounting software. | | +| `description` | *Optional[str]* | :heavy_minus_sign: | Any private, company notes about the transaction. | Transfer from bank account Y to bank account Z | +| `from_` | [shared.TransferTransactionRequestFrom](../../models/shared/transfertransactionrequestfrom.md) | :heavy_check_mark: | N/A | | +| `to` | [shared.TransferTransactionRequestTo](../../models/shared/transfertransactionrequestto.md) | :heavy_check_mark: | N/A | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/from_.md b/sync-for-expenses/docs/models/shared/transfertransactionrequestfrom.md similarity index 90% rename from sync-for-expenses/docs/models/shared/from_.md rename to sync-for-expenses/docs/models/shared/transfertransactionrequestfrom.md index 069b6cda6..03c184186 100644 --- a/sync-for-expenses/docs/models/shared/from_.md +++ b/sync-for-expenses/docs/models/shared/transfertransactionrequestfrom.md @@ -1,9 +1,9 @@ -# From - - -## Fields - -| Field | Type | Required | Description | -| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | -| `account_ref` | [shared.AccountReference](../../models/shared/accountreference.md) | :heavy_check_mark: | Reference of the account you are transferring money from. | +# TransferTransactionRequestFrom + + +## Fields + +| Field | Type | Required | Description | +| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| `account_ref` | [shared.AccountReference](../../models/shared/accountreference.md) | :heavy_check_mark: | N/A | | `amount` | *Decimal* | :heavy_check_mark: | Amount that has been transferred from the account in the native currency of the account. | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/transfertransactionrequestto.md b/sync-for-expenses/docs/models/shared/transfertransactionrequestto.md new file mode 100644 index 000000000..32fd613c2 --- /dev/null +++ b/sync-for-expenses/docs/models/shared/transfertransactionrequestto.md @@ -0,0 +1,9 @@ +# TransferTransactionRequestTo + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | +| `account_ref` | [shared.AccountReference1](../../models/shared/accountreference1.md) | :heavy_check_mark: | N/A | +| `amount` | *Decimal* | :heavy_check_mark: | Amount that has been transferred to the account in the native currency of the account. | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/transfertransactionresponse.md b/sync-for-expenses/docs/models/shared/transfertransactionresponse.md index f2cddc486..c21e39216 100644 --- a/sync-for-expenses/docs/models/shared/transfertransactionresponse.md +++ b/sync-for-expenses/docs/models/shared/transfertransactionresponse.md @@ -1,8 +1,8 @@ -# TransferTransactionResponse - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | +# TransferTransactionResponse + + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | | `sync_id` | *Optional[str]* | :heavy_minus_sign: | Unique id of sync created | cd937d46-8e41-43a9-9477-a79158ffd98a | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/type.md b/sync-for-expenses/docs/models/shared/type.md index efa4c06a7..8e0b630fa 100644 --- a/sync-for-expenses/docs/models/shared/type.md +++ b/sync-for-expenses/docs/models/shared/type.md @@ -1,22 +1,20 @@ -# Type - -The type of phone number - -## Example Usage - -```python -from codat_sync_for_expenses.models.shared import Type - -value = Type.PRIMARY -``` - - -## Values - -| Name | Value | -| ---------- | ---------- | -| `PRIMARY` | Primary | -| `LANDLINE` | Landline | -| `MOBILE` | Mobile | -| `FAX` | Fax | +# Type + +## Example Usage + +```python +from codat_sync_for_expenses.models.shared import Type + +value = Type.FAX +``` + + +## Values + +| Name | Value | +| ---------- | ---------- | +| `FAX` | Fax | +| `LANDLINE` | Landline | +| `MOBILE` | Mobile | +| `PRIMARY` | Primary | | `UNKNOWN` | Unknown | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/updateconnection.md b/sync-for-expenses/docs/models/shared/updateconnection.md new file mode 100644 index 000000000..439e3fee3 --- /dev/null +++ b/sync-for-expenses/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-expenses/docs/models/shared/updatecustomerresponse.md b/sync-for-expenses/docs/models/shared/updatecustomerresponse.md index 10c3776e6..f99ccee35 100644 --- a/sync-for-expenses/docs/models/shared/updatecustomerresponse.md +++ b/sync-for-expenses/docs/models/shared/updatecustomerresponse.md @@ -1,21 +1,21 @@ -# UpdateCustomerResponse - - -## 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` | [OptionalNullable[shared.UpdateCustomerResponseAccountingCustomer]](../../models/shared/updatecustomerresponseaccountingcustomer.md) | :heavy_minus_sign: | N/A | | -| `data_connection_key` | *str* | :heavy_check_mark: | Unique identifier for a company's data connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | -| `data_type` | [Optional[shared.DataType]](../../models/shared/datatype.md) | :heavy_minus_sign: | Available data types | invoices | -| `error_message` | *OptionalNullable[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` | *OptionalNullable[int]* | :heavy_minus_sign: | Number of minutes the push operation must complete within before it times out. | | -| ~~`timeout_in_seconds`~~ | *OptionalNullable[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 +# UpdateCustomerResponse + + +## 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: | The datetime when the push was completed, null if Pending. | | +| `data` | [OptionalNullable[shared.UpdateCustomerResponseAllOfData]](../../models/shared/updatecustomerresponseallofdata.md) | :heavy_minus_sign: | N/A | | +| `data_connection_key` | *str* | :heavy_check_mark: | Unique identifier for a company's data connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | +| `data_type` | [Optional[shared.DataType]](../../models/shared/datatype.md) | :heavy_minus_sign: | Available data types | invoices | +| `error_message` | *OptionalNullable[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: | The datetime when the push was requested. | | +| `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` | *OptionalNullable[int]* | :heavy_minus_sign: | Number of minutes the push operation must complete within before it times out. | | +| ~~`timeout_in_seconds`~~ | *OptionalNullable[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-expenses/docs/models/shared/updatecustomerresponseaccountingcustomer.md b/sync-for-expenses/docs/models/shared/updatecustomerresponseaccountingcustomer.md deleted file mode 100644 index de8148803..000000000 --- a/sync-for-expenses/docs/models/shared/updatecustomerresponseaccountingcustomer.md +++ /dev/null @@ -1,31 +0,0 @@ -# ~~UpdateCustomerResponseAccountingCustomer~~ - -## Overview - -A customer is a person or organisation that buys goods or services. From the Customers endpoints, you can retrieve a [list of all the customers of a company](https://api.codat.io/swagger/index.html#/Customers/get_companies__companyId__data_customers). - -Customers' data links to accounts receivable [invoices](https://docs.codat.io/sync-for-expenses-api#/schemas/Invoice). - - -> :warning: **DEPRECATED**: This will be removed in a future release, please migrate away from it as soon as possible. - - -## Fields - -| Field | Type | Required | Description | Example | -| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `addresses` | List[[shared.Items](../../models/shared/items.md)] | :heavy_minus_sign: | An array of Addresses. | | -| `contact_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the main contact for the identified customer. | | -| `contacts` | List[[shared.Contact](../../models/shared/contact.md)] | :heavy_minus_sign: | An array of Contacts. | | -| `customer_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the customer as recorded in the accounting system, typically the company name. | | -| `default_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 | -| `email_address` | *OptionalNullable[str]* | :heavy_minus_sign: | Email address the customer can be contacted by. | | -| `id` | *Optional[str]* | :heavy_minus_sign: | Identifier for the customer, unique to the company in the accounting software. | | -| `metadata` | [Optional[shared.Metadata]](../../models/shared/metadata.md) | :heavy_minus_sign: | N/A | | -| `modified_date` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `phone` | *OptionalNullable[str]* | :heavy_minus_sign: | Phone number the customer can be contacted by. | | -| `registration_number` | *OptionalNullable[str]* | :heavy_minus_sign: | Company number. In the UK, this is typically the Companies House company registration number. | | -| `source_modified_date` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `status` | [shared.CustomerStatus](../../models/shared/customerstatus.md) | :heavy_check_mark: | Status of customer. | | -| `supplemental_data` | [Optional[shared.SupplementalData]](../../models/shared/supplementaldata.md) | :heavy_minus_sign: | Supplemental data is additional data you can include in our standard data types.

It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. | | -| `tax_number` | *OptionalNullable[str]* | :heavy_minus_sign: | Company tax number. | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/updatecustomerresponseallofdata.md b/sync-for-expenses/docs/models/shared/updatecustomerresponseallofdata.md new file mode 100644 index 000000000..4371b759b --- /dev/null +++ b/sync-for-expenses/docs/models/shared/updatecustomerresponseallofdata.md @@ -0,0 +1,22 @@ +# UpdateCustomerResponseAllOfData + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `addresses` | List[[shared.Items](../../models/shared/items.md)] | :heavy_minus_sign: | An array of Addresses. | +| `contact_name` | *Optional[str]* | :heavy_minus_sign: | Name of the main contact for the identified customer. | +| `contacts` | List[[shared.Contact](../../models/shared/contact.md)] | :heavy_minus_sign: | An array of Contacts. | +| `customer_name` | *Optional[str]* | :heavy_minus_sign: | Name of the customer as recorded in the accounting system, typically the company name. | +| `default_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. | +| `email_address` | *Optional[str]* | :heavy_minus_sign: | Email address the customer can be contacted by. | +| `id` | *Optional[str]* | :heavy_minus_sign: | Identifier for the customer, unique to the company in the accounting software. | +| `metadata` | [Optional[shared.Metadata]](../../models/shared/metadata.md) | :heavy_minus_sign: | N/A | +| `modified_date` | *Optional[str]* | :heavy_minus_sign: | The date when the record was last fetched from the accounting software, commerce software, or open banking provider and updated in Codat’s data cache. Use it to identify and retrieve records that have changed since your last fetch. For example, filtering `modifiedDate` to today will provide new records updated in Codat today. This date is populated for all data types except for attachments, balance sheets, company information, and profit & loss reports ([read more](https://docs.codat.io/using-the-api/modified-dates#modified-date)). In Codat's data model, dates and times are represented using the ISO 8601 standard. | +| `phone` | *Optional[str]* | :heavy_minus_sign: | Phone number the customer can be contacted by. | +| `registration_number` | *Optional[str]* | :heavy_minus_sign: | Company number. In the UK, this is typically the Companies House company registration number. | +| `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` | [shared.CustomerStatus](../../models/shared/customerstatus.md) | :heavy_check_mark: | Current state of the customer. | +| `supplemental_data` | [Optional[shared.SupplementalData]](../../models/shared/supplementaldata.md) | :heavy_minus_sign: | N/A | +| `tax_number` | *Optional[str]* | :heavy_minus_sign: | Company tax number. | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/updateexpenserequest.md b/sync-for-expenses/docs/models/shared/updateexpenserequest.md index 3c54841ec..a01d3bd4a 100644 --- a/sync-for-expenses/docs/models/shared/updateexpenserequest.md +++ b/sync-for-expenses/docs/models/shared/updateexpenserequest.md @@ -1,16 +1,16 @@ -# UpdateExpenseRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `bank_account_ref` | [Optional[shared.UpdateExpenseRequestBankAccountReference]](../../models/shared/updateexpenserequestbankaccountreference.md) | :heavy_minus_sign: | N/A | | -| `contact_ref` | [Optional[shared.ExpenseContactRef]](../../models/shared/expensecontactref.md) | :heavy_minus_sign: | N/A | | -| `currency` | *str* | :heavy_check_mark: | Currency the transaction was recorded in. | GBP | -| `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. \| | | -| `issue_date` | *str* | :heavy_check_mark: | Date the transaction was recorded. | 2022-06-28T00:00:00.000Z | -| `lines` | List[[shared.ExpenseTransactionLine](../../models/shared/expensetransactionline.md)] | :heavy_minus_sign: | Array of transaction lines. | | -| `merchant_name` | *Optional[str]* | :heavy_minus_sign: | Name of the merchant where the purchase took place | Amazon UK | -| `notes` | *Optional[str]* | :heavy_minus_sign: | Any private, company notes about the transaction. | APPLE.COM/BILL - 09001077498 - Card Ending: 4590 | +# UpdateExpenseRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `bank_account_ref` | [Optional[shared.BankAccountReference]](../../models/shared/bankaccountreference.md) | :heavy_minus_sign: | N/A | | +| `contact_ref` | [Optional[shared.ExpenseContactRef]](../../models/shared/expensecontactref.md) | :heavy_minus_sign: | Supplier or Customer for the purchase to be associated to. | | +| `currency` | *str* | :heavy_check_mark: | Currency the transaction was recorded in. | GBP | +| `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. \| | | +| `issue_date` | *str* | :heavy_check_mark: | Date the transaction was recorded. | 2022-06-28T00:00:00.000Z | +| `lines` | List[[shared.ExpenseTransactionLine](../../models/shared/expensetransactionline.md)] | :heavy_minus_sign: | Array of transaction lines. | | +| `merchant_name` | *Optional[str]* | :heavy_minus_sign: | Name of the merchant where the purchase took place | Amazon UK | +| `notes` | *Optional[str]* | :heavy_minus_sign: | Any private, company notes about the transaction. | APPLE.COM/BILL - 09001077498 - Card Ending: 4590 | | `type` | [shared.UpdateExpenseRequestType](../../models/shared/updateexpenserequesttype.md) | :heavy_check_mark: | The type of transaction. | Payment | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/updateexpenserequestbankaccountreference.md b/sync-for-expenses/docs/models/shared/updateexpenserequestbankaccountreference.md deleted file mode 100644 index 17f0eb4dd..000000000 --- a/sync-for-expenses/docs/models/shared/updateexpenserequestbankaccountreference.md +++ /dev/null @@ -1,8 +0,0 @@ -# UpdateExpenseRequestBankAccountReference - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | ------------------------------------ | -| `id` | *Optional[str]* | :heavy_minus_sign: | Identifier of the bank account. | 787dfb37-5707-4dc0-8a86-8d74e4cc78ea | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/updateexpenserequesttype.md b/sync-for-expenses/docs/models/shared/updateexpenserequesttype.md index 2de3891b7..0b2242a18 100644 --- a/sync-for-expenses/docs/models/shared/updateexpenserequesttype.md +++ b/sync-for-expenses/docs/models/shared/updateexpenserequesttype.md @@ -1,21 +1,19 @@ -# UpdateExpenseRequestType - -The type of transaction. - -## Example Usage - -```python -from codat_sync_for_expenses.models.shared import UpdateExpenseRequestType - -value = UpdateExpenseRequestType.PAYMENT -``` - - -## Values - -| Name | Value | -| ------------ | ------------ | -| `PAYMENT` | Payment | -| `REFUND` | Refund | -| `REWARD` | Reward | +# UpdateExpenseRequestType + +## Example Usage + +```python +from codat_sync_for_expenses.models.shared import UpdateExpenseRequestType + +value = UpdateExpenseRequestType.PAYMENT +``` + + +## Values + +| Name | Value | +| ------------ | ------------ | +| `PAYMENT` | Payment | +| `REFUND` | Refund | +| `REWARD` | Reward | | `CHARGEBACK` | Chargeback | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/updateexpenseresponse.md b/sync-for-expenses/docs/models/shared/updateexpenseresponse.md index 4e6366339..ebdac2c22 100644 --- a/sync-for-expenses/docs/models/shared/updateexpenseresponse.md +++ b/sync-for-expenses/docs/models/shared/updateexpenseresponse.md @@ -1,8 +1,8 @@ -# UpdateExpenseResponse - - -## Fields - -| Field | Type | Required | Description | Example | -| ---------------------------------------------- | ---------------------------------------------- | ---------------------------------------------- | ---------------------------------------------- | ---------------------------------------------- | +# UpdateExpenseResponse + + +## Fields + +| Field | Type | Required | Description | Example | +| ---------------------------------------------- | ---------------------------------------------- | ---------------------------------------------- | ---------------------------------------------- | ---------------------------------------------- | | `sync_id` | *Optional[str]* | :heavy_minus_sign: | Unique identifier for the update expense sync. | 1ad0695c-4566-4715-918c-adbb03eac81e | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/updatereimbursableexpensetransactionrequest.md b/sync-for-expenses/docs/models/shared/updatereimbursableexpensetransactionrequest.md index f6255e33c..0ac82a07f 100644 --- a/sync-for-expenses/docs/models/shared/updatereimbursableexpensetransactionrequest.md +++ b/sync-for-expenses/docs/models/shared/updatereimbursableexpensetransactionrequest.md @@ -1,16 +1,16 @@ -# UpdateReimbursableExpenseTransactionRequest - - -## Fields - -| Field | Type | Required | Description | Example | -| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `ap_account_ref` | [OptionalNullable[shared.ApAccountRef]](../../models/shared/apaccountref.md) | :heavy_minus_sign: | N/A | | -| `contact_ref` | [shared.ReimbursementContactRef](../../models/shared/reimbursementcontactref.md) | :heavy_check_mark: | N/A | | -| `currency` | *str* | :heavy_check_mark: | Currency the transaction was recorded in. | GBP | -| `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: | 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 | -| `issue_date` | *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 | -| `lines` | List[[shared.ReimbursableExpenseTransactionLine](../../models/shared/reimbursableexpensetransactionline.md)] | :heavy_minus_sign: | Array of transaction lines. | | -| `notes` | *Optional[str]* | :heavy_minus_sign: | Any private, company notes about the transaction. | APPLE.COM/BILL - 09001077498 - Card Ending: 4590 | +# UpdateReimbursableExpenseTransactionRequest + + +## Fields + +| Field | Type | Required | Description | Example | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `ap_account_ref` | [OptionalNullable[shared.ApAccountRef]](../../models/shared/apaccountref.md) | :heavy_minus_sign: | N/A | | +| `contact_ref` | [shared.ReimbursementContactRef](../../models/shared/reimbursementcontactref.md) | :heavy_check_mark: | N/A | | +| `currency` | *str* | :heavy_check_mark: | Currency the transaction was recorded in. | GBP | +| `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 transaction was recorded. | | +| `lines` | List[[shared.ReimbursableExpenseTransactionLine](../../models/shared/reimbursableexpensetransactionline.md)] | :heavy_minus_sign: | Array of transaction lines. | | +| `notes` | *Optional[str]* | :heavy_minus_sign: | Any private, company notes about the transaction. | APPLE.COM/BILL - 09001077498 - Card Ending: 4590 | | `reference` | *OptionalNullable[str]* | :heavy_minus_sign: | User-friendly reference for the reimbursable expense. | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/updatesupplierresponse.md b/sync-for-expenses/docs/models/shared/updatesupplierresponse.md index 9378b0397..94aca1cca 100644 --- a/sync-for-expenses/docs/models/shared/updatesupplierresponse.md +++ b/sync-for-expenses/docs/models/shared/updatesupplierresponse.md @@ -1,21 +1,21 @@ -# UpdateSupplierResponse - - -## 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` | [OptionalNullable[shared.UpdateSupplierResponseAccountingSupplier]](../../models/shared/updatesupplierresponseaccountingsupplier.md) | :heavy_minus_sign: | N/A | {
"id": "C520FFD4-F6F6-4FC2-A6D2-5D7088B2B14F",
"supplierName": "Kelly's Industrial Supplies",
"contactName": "Kelly's Industrial Supplies",
"emailAddress": "sales@kellysupplies.com",
"phone": "07999 999999",
"addresses": [
{
"type": "Billing",
"line1": "Unit 51",
"line2": "Bakersfield Industrial Estate",
"city": "Bakersfield",
"region": "California",
"country": "USA",
"postalcode": "93308"
}
],
"registrationNumber": "string",
"taxNumber": "string",
"status": "Unknown",
"defaultCurrency": "string",
"metadata": {
"isDeleted": true
},
"supplementalData": {
"content": {
"property1": {
"property1": null,
"property2": null
},
"property2": {
"property1": null,
"property2": null
}
}
},
"modifiedDate": "2022-10-23T00:00:00Z",
"sourceModifiedDate": "2022-10-23T00:00:00Z"
} | -| `data_connection_key` | *str* | :heavy_check_mark: | Unique identifier for a company's data connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | -| `data_type` | [Optional[shared.DataType]](../../models/shared/datatype.md) | :heavy_minus_sign: | Available data types | invoices | -| `error_message` | *OptionalNullable[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` | *OptionalNullable[int]* | :heavy_minus_sign: | Number of minutes the push operation must complete within before it times out. | | -| ~~`timeout_in_seconds`~~ | *OptionalNullable[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 +# UpdateSupplierResponse + + +## 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: | The datetime when the push was completed, null if Pending. | | +| `data` | [OptionalNullable[shared.UpdateSupplierResponseAllOfData]](../../models/shared/updatesupplierresponseallofdata.md) | :heavy_minus_sign: | N/A | {
"id": "C520FFD4-F6F6-4FC2-A6D2-5D7088B2B14F",
"supplierName": "Kelly's Industrial Supplies",
"contactName": "Kelly's Industrial Supplies",
"emailAddress": "sales@kellysupplies.com",
"phone": "07999 999999",
"addresses": [
{
"type": "Billing",
"line1": "Unit 51",
"line2": "Bakersfield Industrial Estate",
"city": "Bakersfield",
"region": "California",
"country": "USA",
"postalcode": "93308"
}
],
"registrationNumber": "string",
"taxNumber": "string",
"status": "Unknown",
"defaultCurrency": "string",
"metadata": {
"isDeleted": true
},
"supplementalData": {
"content": {
"property1": {
"property1": null,
"property2": null
},
"property2": {
"property1": null,
"property2": null
}
}
},
"modifiedDate": "2022-10-23T00:00:00Z",
"sourceModifiedDate": "2022-10-23T00:00:00Z"
} | +| `data_connection_key` | *str* | :heavy_check_mark: | Unique identifier for a company's data connection. | 2e9d2c44-f675-40ba-8049-353bfcb5e171 | +| `data_type` | [Optional[shared.DataType]](../../models/shared/datatype.md) | :heavy_minus_sign: | Available data types | invoices | +| `error_message` | *OptionalNullable[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: | The datetime when the push was requested. | | +| `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` | *OptionalNullable[int]* | :heavy_minus_sign: | Number of minutes the push operation must complete within before it times out. | | +| ~~`timeout_in_seconds`~~ | *OptionalNullable[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-expenses/docs/models/shared/updatesupplierresponseaccountingsupplier.md b/sync-for-expenses/docs/models/shared/updatesupplierresponseaccountingsupplier.md deleted file mode 100644 index 637f71bd3..000000000 --- a/sync-for-expenses/docs/models/shared/updatesupplierresponseaccountingsupplier.md +++ /dev/null @@ -1,27 +0,0 @@ -# ~~UpdateSupplierResponseAccountingSupplier~~ - -## Overview - -From the **Suppliers** endpoints, you can retrieve a list of [all the suppliers for a company](https://docs.codat.io/sync-for-expenses-api#/operations/list-suppliers). Suppliers' data links to accounts payable [bills](https://docs.codat.io/sync-for-expenses-api#/schemas/Bill). - -> :warning: **DEPRECATED**: This will be removed in a future release, please migrate away from it as soon as possible. - - -## Fields - -| Field | Type | Required | Description | Example | -| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `addresses` | List[[shared.Items](../../models/shared/items.md)] | :heavy_minus_sign: | An array of Addresses. | | -| `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. | | -| `metadata` | [Optional[shared.Metadata]](../../models/shared/metadata.md) | :heavy_minus_sign: | N/A | | -| `modified_date` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `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 | -| `registration_number` | *OptionalNullable[str]* | :heavy_minus_sign: | Company number of the supplier. In the UK, this is typically the company registration number issued by Companies House. | | -| `source_modified_date` | *Optional[str]* | :heavy_minus_sign: | N/A | **Example 1:** 2022-10-23T00:00:00Z
**Example 2:** 2022-10-23 | -| `status` | [shared.SupplierStatus](../../models/shared/supplierstatus.md) | :heavy_check_mark: | Status of the supplier. | | -| `supplemental_data` | [Optional[shared.SupplementalData]](../../models/shared/supplementaldata.md) | :heavy_minus_sign: | Supplemental data is additional data you can include in our standard data types.

It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. | | -| `supplier_name` | *OptionalNullable[str]* | :heavy_minus_sign: | Name of the supplier as recorded in the accounting system, typically the company name. | | -| `tax_number` | *OptionalNullable[str]* | :heavy_minus_sign: | Supplier's company tax number. | | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/updatesupplierresponseallofdata.md b/sync-for-expenses/docs/models/shared/updatesupplierresponseallofdata.md new file mode 100644 index 000000000..c878dc995 --- /dev/null +++ b/sync-for-expenses/docs/models/shared/updatesupplierresponseallofdata.md @@ -0,0 +1,21 @@ +# UpdateSupplierResponseAllOfData + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `addresses` | List[[shared.Items](../../models/shared/items.md)] | :heavy_minus_sign: | An array of Addresses. | +| `contact_name` | *Optional[str]* | :heavy_minus_sign: | Name of the main contact for the supplier. | +| `default_currency` | *Optional[str]* | :heavy_minus_sign: | Default currency the supplier's transactional data is recorded in. | +| `email_address` | *Optional[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. | +| `metadata` | [Optional[shared.Metadata]](../../models/shared/metadata.md) | :heavy_minus_sign: | N/A | +| `modified_date` | *Optional[str]* | :heavy_minus_sign: | The date when the record was last fetched from the accounting software, commerce software, or open banking provider and updated in Codat’s data cache. Use it to identify and retrieve records that have changed since your last fetch. For example, filtering `modifiedDate` to today will provide new records updated in Codat today. This date is populated for all data types except for attachments, balance sheets, company information, and profit & loss reports ([read more](https://docs.codat.io/using-the-api/modified-dates#modified-date)). In Codat's data model, dates and times are represented using the ISO 8601 standard. | +| `phone` | *Optional[str]* | :heavy_minus_sign: | Phone number that the supplier may be contacted on. | +| `registration_number` | *Optional[str]* | :heavy_minus_sign: | Company number of the supplier. In the UK, this is typically the company registration number issued by Companies House. | +| `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` | [shared.SupplierStatus](../../models/shared/supplierstatus.md) | :heavy_check_mark: | N/A | +| `supplemental_data` | [Optional[shared.SupplementalData]](../../models/shared/supplementaldata.md) | :heavy_minus_sign: | N/A | +| `supplier_name` | *Optional[str]* | :heavy_minus_sign: | Name of the supplier as recorded in the accounting system, typically the company name. | +| `tax_number` | *Optional[str]* | :heavy_minus_sign: | Supplier's company tax number. | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/validation.md b/sync-for-expenses/docs/models/shared/validation.md index 4cfc544dc..b208342e2 100644 --- a/sync-for-expenses/docs/models/shared/validation.md +++ b/sync-for-expenses/docs/models/shared/validation.md @@ -1,11 +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 | +# 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-expenses/docs/models/shared/validationitem.md b/sync-for-expenses/docs/models/shared/validationitem.md index 1aaf084c9..791ee2076 100644 --- a/sync-for-expenses/docs/models/shared/validationitem.md +++ b/sync-for-expenses/docs/models/shared/validationitem.md @@ -1,10 +1,11 @@ -# ValidationItem - - -## 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. | +# ValidationItem + + +## Fields + +| Field | Type | Required | Description | +| -------------------------------------------- | -------------------------------------------- | -------------------------------------------- | -------------------------------------------- | +| `additional_properties` | Dict[str, *Any*] | :heavy_check_mark: | N/A | +| `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-expenses/docs/models/shared/validdatatypelinks.md b/sync-for-expenses/docs/models/shared/validdatatypelinks.md index 809a80db0..7715cebea 100644 --- a/sync-for-expenses/docs/models/shared/validdatatypelinks.md +++ b/sync-for-expenses/docs/models/shared/validdatatypelinks.md @@ -1,50 +1,50 @@ -# ValidDataTypeLinks - -When querying Codat's data model, some data types return `validDatatypeLinks` metadata in the JSON response. This indicates where that object can be used as a reference—a _valid link_—when creating or updating other data. - -For example, `validDatatypeLinks` might indicate the following references: - -- Which tax rates are valid to use on the line item of a bill. -- Which items can be used when creating an invoice. - -You can use `validDatatypeLinks` to present your SMB customers with only valid choices when selecting objects from a list, for example. - -## `validDatatypeLinks` example - -The following example uses the `Accounting.Accounts` data type. It shows that, on the linked integration, this account is valid as the account on a payment or bill payment; and as the account referenced on the line item of a direct income or direct cost. Because there is no valid link to Invoices or Bills, using this account on those data types will result in an error. - -```json validDatatypeLinks for an account -{ - "id": "bd9e85e0-0478-433d-ae9f-0b3c4f04bfe4", - "nominalCode": "090", - "name": "Business Bank Account", - #... - "validDatatypeLinks": [ - { - "property": "Id", - "links": [ - "Payment.AccountRef.Id", - "BillPayment.AccountRef.Id", - "DirectIncome.LineItems.AccountRef.Id", - "DirectCost.LineItems.AccountRef.Id" - ] - } - ] - } -``` - - - -## Support for `validDatatypeLinks` - -Codat currently supports `validDatatypeLinks` for some data types on our Xero, QuickBooks Online, QuickBooks Desktop, Exact (NL), and Sage Business Cloud integrations. - -If you'd like us to extend support to more data types or integrations, suggest or vote for this on our Product Roadmap. - - -## Fields - -| Field | Type | Required | Description | -| ------------------------------------------------------- | ------------------------------------------------------- | ------------------------------------------------------- | ------------------------------------------------------- | -| `links` | List[*str*] | :heavy_minus_sign: | Supported `dataTypes` that the record can be linked to. | +# ValidDataTypeLinks + +When querying Codat's data model, some data types return `validDatatypeLinks` metadata in the JSON response. This indicates where that object can be used as a reference—a _valid link_—when creating or updating other data. + +For example, `validDatatypeLinks` might indicate the following references: + +- Which tax rates are valid to use on the line item of a bill. +- Which items can be used when creating an invoice. + +You can use `validDatatypeLinks` to present your SMB customers with only valid choices when selecting objects from a list, for example. + +## `validDatatypeLinks` example + +The following example uses the `Accounting.Accounts` data type. It shows that, on the linked integration, this account is valid as the account on a payment or bill payment; and as the account referenced on the line item of a direct income or direct cost. Because there is no valid link to Invoices or Bills, using this account on those data types will result in an error. + +```json validDatatypeLinks for an account +{ + "id": "bd9e85e0-0478-433d-ae9f-0b3c4f04bfe4", + "nominalCode": "090", + "name": "Business Bank Account", + #... + "validDatatypeLinks": [ + { + "property": "Id", + "links": [ + "Payment.AccountRef.Id", + "BillPayment.AccountRef.Id", + "DirectIncome.LineItems.AccountRef.Id", + "DirectCost.LineItems.AccountRef.Id" + ] + } + ] + } +``` + + + +## Support for `validDatatypeLinks` + +Codat currently supports `validDatatypeLinks` for some data types on our Xero, QuickBooks Online, QuickBooks Desktop, Exact (NL), and Sage Business Cloud integrations. + +If you'd like us to extend support to more data types or integrations, suggest or vote for this on our Product Roadmap. + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------- | ------------------------------------------------------- | ------------------------------------------------------- | ------------------------------------------------------- | +| `links` | List[*str*] | :heavy_minus_sign: | Supported `dataTypes` that the record can be linked to. | | `property` | *OptionalNullable[str]* | :heavy_minus_sign: | The property from the account that can be linked. | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/validfor.md b/sync-for-expenses/docs/models/shared/validfor.md index 112c68ea0..5417b3cba 100644 --- a/sync-for-expenses/docs/models/shared/validfor.md +++ b/sync-for-expenses/docs/models/shared/validfor.md @@ -1,22 +1,22 @@ -# ValidFor - -## Example Usage - -```python -from codat_sync_for_expenses.models.shared import ValidFor - -value = ValidFor.EXPENSE_TRANSACTIONS_PAYMENT -``` - - -## Values - -| Name | Value | -| ----------------------------------- | ----------------------------------- | -| `EXPENSE_TRANSACTIONS_PAYMENT` | expense-transactions.Payment | -| `EXPENSE_TRANSACTIONS_REFUND` | expense-transactions.Refund | -| `EXPENSE_TRANSACTIONS_REWARD` | expense-transactions.Reward | -| `EXPENSE_TRANSACTIONS_CHARGEBACK` | expense-transactions.Chargeback | -| `REIMBURSABLE_EXPENSE_TRANSACTIONS` | reimbursable-expense-transactions | -| `TRANSFER_TRANSACTIONS` | transfer-transactions | +# ValidFor + +## Example Usage + +```python +from codat_sync_for_expenses.models.shared import ValidFor + +value = ValidFor.EXPENSE_TRANSACTIONS_PAYMENT +``` + + +## Values + +| Name | Value | +| ----------------------------------- | ----------------------------------- | +| `EXPENSE_TRANSACTIONS_PAYMENT` | expense-transactions.Payment | +| `EXPENSE_TRANSACTIONS_REFUND` | expense-transactions.Refund | +| `EXPENSE_TRANSACTIONS_REWARD` | expense-transactions.Reward | +| `EXPENSE_TRANSACTIONS_CHARGEBACK` | expense-transactions.Chargeback | +| `REIMBURSABLE_EXPENSE_TRANSACTIONS` | reimbursable-expense-transactions | +| `TRANSFER_TRANSACTIONS` | transfer-transactions | | `ADJUSTMENT_TRANSACTIONS` | adjustment-transactions | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/validtransactiontypes.md b/sync-for-expenses/docs/models/shared/validtransactiontypes.md index 05e8fcbc5..ef7e17430 100644 --- a/sync-for-expenses/docs/models/shared/validtransactiontypes.md +++ b/sync-for-expenses/docs/models/shared/validtransactiontypes.md @@ -1,19 +1,19 @@ -# ValidTransactionTypes - -## Example Usage - -```python -from codat_sync_for_expenses.models.shared import ValidTransactionTypes - -value = ValidTransactionTypes.PAYMENT -``` - - -## Values - -| Name | Value | -| ------------ | ------------ | -| `PAYMENT` | Payment | -| `REFUND` | Refund | -| `REWARD` | Reward | +# ValidTransactionTypes + +## Example Usage + +```python +from codat_sync_for_expenses.models.shared import ValidTransactionTypes + +value = ValidTransactionTypes.PAYMENT +``` + + +## Values + +| Name | Value | +| ------------ | ------------ | +| `PAYMENT` | Payment | +| `REFUND` | Refund | +| `REWARD` | Reward | | `CHARGEBACK` | Chargeback | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/shared/weblink.md b/sync-for-expenses/docs/models/shared/weblink.md index bb96fcb0b..82d87da6d 100644 --- a/sync-for-expenses/docs/models/shared/weblink.md +++ b/sync-for-expenses/docs/models/shared/weblink.md @@ -1,11 +1,11 @@ -# Weblink - -Weblink associated with the company. - - -## Fields - -| Field | Type | Required | Description | -| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | -| `type` | [Optional[shared.CompanyInformationSchemasType]](../../models/shared/companyinformationschemastype.md) | :heavy_minus_sign: | The type of the weblink. | +# Weblink + +Weblink associated with the company. + + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | +| `type` | [Optional[shared.CompanyInformationSchemasType]](../../models/shared/companyinformationschemastype.md) | :heavy_minus_sign: | The type of the weblink. | | `url` | *Optional[str]* | :heavy_minus_sign: | The full URL for the weblink. | \ No newline at end of file diff --git a/sync-for-expenses/docs/models/utils/retryconfig.md b/sync-for-expenses/docs/models/utils/retryconfig.md index 69dd549ec..0977111b8 100644 --- a/sync-for-expenses/docs/models/utils/retryconfig.md +++ b/sync-for-expenses/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-expenses/docs/sdks/accounts/README.md b/sync-for-expenses/docs/sdks/accounts/README.md index 71f286a99..9063ec059 100644 --- a/sync-for-expenses/docs/sdks/accounts/README.md +++ b/sync-for-expenses/docs/sdks/accounts/README.md @@ -1,335 +1,335 @@ -# Accounts - -## Overview - -Create accounts and view create account options. - -### Available Operations - -* [create](#create) - Create account -* [get_create_model](#get_create_model) - Get create account model - -## create - -The *Create account* endpoint creates a new [account](https://docs.codat.io/sync-for-expenses-api#/schemas/Account) for a given company's connection. - -[Accounts](https://docs.codat.io/sync-for-expenses-api#/schemas/Account) are the categories a business uses to record accounting transactions. - -**Integration-specific behavior** - -Required data may vary by integration. To see what data to post, first call [Get create account model](https://docs.codat.io/sync-for-expenses-api#/operations/get-create-chartOfAccounts-model). - -### Example Usage - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared -from decimal import Decimal - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.accounts.create(request={ - "account_prototype": { - "currency": "GBP", - "current_balance": Decimal("0"), - "description": "Invoices the business has issued but has not yet collected payment on.", - "fully_qualified_category": "Asset.Current", - "fully_qualified_name": "Cash On Hand", - "name": "Accounts Receivable", - "nominal_code": "610", - "status": shared.AccountStatus.ACTIVE, - "type": shared.AccountType.ASSET, - }, - "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.CreateAccountRequest](../../models/operations/createaccountrequest.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.CreateAccountResponse](../../models/shared/createaccountresponse.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 | \*/\* | - -## get_create_model - -The *Get create account model* endpoint returns the expected data for the request payload when creating an [account](https://docs.codat.io/sync-for-expenses-api#/schemas/Account) for a given company and integration. - -[Accounts](https://docs.codat.io/sync-for-expenses-api#/schemas/Account) are the categories a business uses to record accounting transactions. - -**Integration-specific behavior** - -See the *response examples* for integration-specific indicative models. - -### Example Usage: Exact (Netherlands) - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.accounts.get_create_model(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - }) - - # Handle response - print(res) - -``` -### Example Usage: Exact (UK) - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.accounts.get_create_model(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - }) - - # Handle response - print(res) - -``` -### Example Usage: MYOB AccountRight and Essentials - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.accounts.get_create_model(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - }) - - # Handle response - print(res) - -``` -### Example Usage: QuickBooks Desktop - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.accounts.get_create_model(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - }) - - # Handle response - print(res) - -``` -### Example Usage: QuickBooks Online - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.accounts.get_create_model(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - }) - - # Handle response - print(res) - -``` -### Example Usage: QuickBooks Online Sandbox - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.accounts.get_create_model(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - }) - - # Handle response - print(res) - -``` -### Example Usage: Sage Business Cloud Accounting - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.accounts.get_create_model(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - }) - - # Handle response - print(res) - -``` -### Example Usage: Sage Intacct - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.accounts.get_create_model(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - }) - - # Handle response - print(res) - -``` -### Example Usage: Sandbox - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.accounts.get_create_model(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - }) - - # Handle response - print(res) - -``` -### Example Usage: Xero - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.accounts.get_create_model(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.GetCreateChartOfAccountsModelRequest](../../models/operations/getcreatechartofaccountsmodelrequest.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.PushOption](../../models/shared/pushoption.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | +# Accounts + +## Overview + +Create accounts and view create account options. + +### Available Operations + +* [create](#create) - Create account +* [get_create_model](#get_create_model) - Get create account model + +## create + +The *Create account* endpoint creates a new [account](https://docs.codat.io/sync-for-expenses-api#/schemas/Account) for a given company's connection. + +[Accounts](https://docs.codat.io/sync-for-expenses-api#/schemas/Account) are the categories a business uses to record accounting transactions. + +**Integration-specific behavior** + +Required data may vary by integration. To see what data to post, first call [Get create account model](https://docs.codat.io/sync-for-expenses-api#/operations/get-create-chartOfAccounts-model). + +### Example Usage + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared +from decimal import Decimal + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.accounts.create(request={ + "account_prototype": { + "currency": "GBP", + "current_balance": Decimal("0"), + "description": "Invoices the business has issued but has not yet collected payment on.", + "fully_qualified_category": "Asset.Current", + "fully_qualified_name": "Cash On Hand", + "name": "Accounts Receivable", + "nominal_code": "610", + "status": shared.AccountStatus.ACTIVE, + "type": shared.AccountType.ASSET, + }, + "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.CreateAccountRequest](../../models/operations/createaccountrequest.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.CreateAccountResponse](../../models/shared/createaccountresponse.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 | \*/\* | + +## get_create_model + +The *Get create account model* endpoint returns the expected data for the request payload when creating an [account](https://docs.codat.io/sync-for-expenses-api#/schemas/Account) for a given company and integration. + +[Accounts](https://docs.codat.io/sync-for-expenses-api#/schemas/Account) are the categories a business uses to record accounting transactions. + +**Integration-specific behavior** + +See the *response examples* for integration-specific indicative models. + +### Example Usage: Exact (Netherlands) + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.accounts.get_create_model(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` +### Example Usage: Exact (UK) + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.accounts.get_create_model(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` +### Example Usage: MYOB AccountRight and Essentials + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.accounts.get_create_model(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` +### Example Usage: QuickBooks Desktop + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.accounts.get_create_model(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` +### Example Usage: QuickBooks Online + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.accounts.get_create_model(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` +### Example Usage: QuickBooks Online Sandbox + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.accounts.get_create_model(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` +### Example Usage: Sage Business Cloud Accounting + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.accounts.get_create_model(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` +### Example Usage: Sage Intacct + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.accounts.get_create_model(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` +### Example Usage: Sandbox + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.accounts.get_create_model(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` +### Example Usage: Xero + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.accounts.get_create_model(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.GetCreateChartOfAccountsModelRequest](../../models/operations/getcreatechartofaccountsmodelrequest.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.PushOption](../../models/shared/pushoption.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-expenses/docs/sdks/adjustments/README.md b/sync-for-expenses/docs/sdks/adjustments/README.md index 256d7d866..69c761f37 100644 --- a/sync-for-expenses/docs/sdks/adjustments/README.md +++ b/sync-for-expenses/docs/sdks/adjustments/README.md @@ -1,163 +1,110 @@ -# Adjustments - -## Overview - -Create transactions that represent your adjustments to your customers' spend. - -### Available Operations - -* [create](#create) - Create adjustment transaction - -## create - -Use the *Create adjustment expense* endpoint to create an [adjustment](https://docs.codat.io/sync-for-expenses-api#/schemas/AdjustmentTransactionRequest) in the accounting software for a given company's connection. - -Adjustments represent write-offs and transaction alterations, such as foreign exchange adjustments, in the form of a journal entry. - -### Supported Integrations - -| Integration | Supported | -|-----------------------|-----------| -| QuickBooks Desktop | Yes | - -### Example Usage: Create adjustment - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared -from decimal import Decimal - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.adjustments.create(request={ - "request_body": [ - { - "currency": "USD", - "currency_rate": Decimal("1"), - "date_": "2024-05-21T00:00:00+00:00", - "id": "3357b3df-5f2e-465d-b9ba-226519dbb8f1", - "lines": [ - { - "account_ref": { - "id": "80000018-1671793811", - }, - "amount": Decimal("50"), - "description": "debit line", - "invoice_to": { - "id": "80000002-1674552702", - "type": shared.InvoiceToType.CUSTOMER, - }, - "tracking_refs": [ - { - "id": "80000003-1674553958", - }, - ], - }, - { - "account_ref": { - "id": "80000028-1671794219", - }, - "amount": Decimal("-50"), - "description": "credit line", - "tracking_refs": [ - { - "id": "80000003-1674553958", - }, - ], - }, - ], - "reference": "test reference", - }, - ], - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` -### Example Usage: Example 1 - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.adjustments.create(request={ - "request_body": [ - { - "currency": "Iraqi Dinar", - "date_": "2022-10-23T00:00:00Z", - "id": "a13b8cfd-4823-489f-b930-8d52faa3dc07", - "lines": [], - }, - ], - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` -### Example Usage: Malformed query - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.adjustments.create(request={ - "request_body": [ - { - "currency": "Iraqi Dinar", - "date_": "2022-10-23T00:00:00Z", - "id": "a13b8cfd-4823-489f-b930-8d52faa3dc07", - "lines": [], - }, - ], - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| -------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | -| `request` | [operations.CreateAdjustmentTransactionRequest](../../models/operations/createadjustmenttransactionrequest.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.AdjustmentTransactionResponse](../../models/shared/adjustmenttransactionresponse.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ---------------------------- | ---------------------------- | ---------------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | +# Adjustments + +## Overview + +Create transactions that represent your adjustments to your customers' spend. + +### Available Operations + +* [create](#create) - Create adjustment transaction + +## create + +Use the *Create adjustment expense* endpoint to create an [adjustment](https://docs.codat.io/sync-for-expenses-api#/schemas/AdjustmentTransactionRequest) in the accounting software for a given company's connection. + +Adjustments represent write-offs and transaction alterations, such as foreign exchange adjustments, in the form of a journal entry. + +### Supported Integrations + +| Integration | Supported | +|-----------------------|-----------| +| QuickBooks Desktop | Yes | + +### Example Usage: Create adjustment + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.adjustments.create(request={ + "request_body": [], + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` +### Example Usage: Example 1 + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.adjustments.create(request={ + "request_body": [], + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` +### Example Usage: Malformed query + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.adjustments.create(request={ + "request_body": [], + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| -------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | +| `request` | [operations.CreateAdjustmentTransactionRequest](../../models/operations/createadjustmenttransactionrequest.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.AdjustmentTransactionResponse](../../models/shared/adjustmenttransactionresponse.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-expenses/docs/sdks/attachments/README.md b/sync-for-expenses/docs/sdks/attachments/README.md index 0da303ab5..f922961ef 100644 --- a/sync-for-expenses/docs/sdks/attachments/README.md +++ b/sync-for-expenses/docs/sdks/attachments/README.md @@ -1,73 +1,73 @@ -# Attachments - -## Overview - -Attach receipts to a transaction for a complete audit trail. - -### Available Operations - -* [upload](#upload) - Upload attachment - -## upload - -The *Upload attachment* endpoint uploads an attachment in the accounting software against the given transactionId. - -[Expense transactions](https://docs.codat.io/sync-for-expenses-api#/schemas/ExpenseTransaction) represent transactions made with a company debit or credit card. Attachments for `Adjustment` and `Transfer` transaction types are not supported for any integrations. - -**Integration-specific behavior** - -Each accounting software supports different file formats and sizes. - -| Integration | File size | File extension | Supported transactions | -|-----------------------------------|-----------|-------------------------------------------------------|------------------------| -| **Xero** | 3 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 | All supported types | -| **QuickBooks Online** | 100 MB | AI, CSV, DOC, DOCX, EPS, GIF, JPEG, JPG, ODS, PAGES, PDF, PNG, RTF, TIF, TXT, XLS, XLSX, XML | `expense-transactions.Payment`, `expense-transactions.Refund`, `reimbursable-expense-transactions` | -| **NetSuite** | 100 MB | BMP, CSV, XLS, XLSX, JSON, PDF, PJPG, PJPEG, PNG, TXT, SVG, TIF, TIFF, DOC, DOCX, ZIP |`expense-transactions.Payment`, `expense-transactions.Refund` | -| **Dynamics 365 Business Central** | 350 MB | [No explicit requirements outlined](https://learn.microsoft.com/en-gb/dynamics365/business-central/ui-how-add-link-to-record#to-attach-a-file-to-a-purchase-invoice) for text, image, and video files. | All supported types -| **QuickBooks Desktop** | NA | Does not support attachment upload | N/A | -| **FreeAgent** | 5MB | PNG, X-PNG, JPEG, PJG, GIF, X-PDF | `expense-transactions.Payment`, `reimbursable-expense-transactions` -| **Zoho Books** | 5MB | GIF, PNG, JPEG, JPG, BMP, PDF | `expense-transactions.Payment`, `reimbursable-expense-transactions` | - -### Example Usage - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.attachments.upload(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "sync_id": "6fb40d5e-b13e-11ed-afa1-0242ac120002", - "transaction_id": "336694d8-2dca-4cb5-a28d-3ccb83e55eee", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | -| `request` | [operations.UploadExpenseAttachmentRequest](../../models/operations/uploadexpenseattachmentrequest.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 | +# Attachments + +## Overview + +Attach receipts to a transaction for a complete audit trail. + +### Available Operations + +* [upload](#upload) - Upload attachment + +## upload + +The *Upload attachment* endpoint uploads an attachment in the accounting software against the given transactionId. + +[Expense transactions](https://docs.codat.io/sync-for-expenses-api#/schemas/ExpenseTransaction) represent transactions made with a company debit or credit card. Attachments for `Adjustment` and `Transfer` transaction types are not supported for any integrations. + +**Integration-specific behavior** + +Each accounting software supports different file formats and sizes. + +| Integration | File size | File extension | Supported transactions | +|-----------------------------------|-----------|-------------------------------------------------------|------------------------| +| **Xero** | 3 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 | All supported types | +| **QuickBooks Online** | 100 MB | AI, CSV, DOC, DOCX, EPS, GIF, JPEG, JPG, ODS, PAGES, PDF, PNG, RTF, TIF, TXT, XLS, XLSX, XML | `expense-transactions.Payment`, `expense-transactions.Refund`, `reimbursable-expense-transactions` | +| **NetSuite** | 100 MB | BMP, CSV, XLS, XLSX, JSON, PDF, PJPG, PJPEG, PNG, TXT, SVG, TIF, TIFF, DOC, DOCX, ZIP |`expense-transactions.Payment`, `expense-transactions.Refund` | +| **Dynamics 365 Business Central** | 350 MB | [No explicit requirements outlined](https://learn.microsoft.com/en-gb/dynamics365/business-central/ui-how-add-link-to-record#to-attach-a-file-to-a-purchase-invoice) for text, image, and video files. | All supported types +| **QuickBooks Desktop** | NA | Does not support attachment upload | N/A | +| **FreeAgent** | 5MB | PNG, X-PNG, JPEG, PJG, GIF, X-PDF | `expense-transactions.Payment`, `reimbursable-expense-transactions` +| **Zoho Books** | 5MB | GIF, PNG, JPEG, JPG, BMP, PDF | `expense-transactions.Payment`, `reimbursable-expense-transactions` | + +### Example Usage + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.attachments.upload(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "sync_id": "6fb40d5e-b13e-11ed-afa1-0242ac120002", + "transaction_id": "336694d8-2dca-4cb5-a28d-3ccb83e55eee", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | +| `request` | [operations.UploadExpenseAttachmentRequest](../../models/operations/uploadexpenseattachmentrequest.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 | \*/\* | \ No newline at end of file diff --git a/sync-for-expenses/docs/sdks/bankaccounts/README.md b/sync-for-expenses/docs/sdks/bankaccounts/README.md index a68f84a84..0c8657027 100644 --- a/sync-for-expenses/docs/sdks/bankaccounts/README.md +++ b/sync-for-expenses/docs/sdks/bankaccounts/README.md @@ -1,368 +1,368 @@ -# BankAccounts - -## Overview - -Create bank accounts and view create bank account options. - -### Available Operations - -* [create](#create) - Create bank account -* [get_create_model](#get_create_model) - Get create bank account model - -## create - -The *Create bank account* endpoint creates a new [bank account](https://docs.codat.io/sync-for-expenses-api#/schemas/BankAccount) for a given company's connection. - -[Bank accounts](https://docs.codat.io/sync-for-expenses-api#/schemas/BankAccount) are financial accounts maintained by a bank or other financial institution. - -**Integration-specific behavior** - -Required data may vary by integration. To see what data to post, first call [Get create/update bank account model](https://docs.codat.io/sync-for-expenses-api#/operations/get-create-update-bankAccounts-model). - -### Example Usage: Malformed query - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.bank_accounts.create(request={ - "bank_account": { - "currency": "GBP", - "modified_date": "2022-10-23T00:00:00Z", - "source_modified_date": "2022-10-23T00:00:00Z", - "status": shared.BankAccountStatus.ACTIVE, - }, - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - }) - - # Handle response - print(res) - -``` -### Example Usage: QuickBooks Online - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.bank_accounts.create(request={ - "bank_account": { - "account_name": "GBP Bank Account", - "account_number": "12345678", - "account_type": shared.BankAccountType.DEBIT, - "currency": "GBP", - "status": shared.BankAccountStatus.ACTIVE, - }, - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - }) - - # Handle response - print(res) - -``` -### Example Usage: Xero - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.bank_accounts.create(request={ - "bank_account": { - "account_name": "Xero GBP Bank Account", - "account_number": "12345678", - "account_type": shared.BankAccountType.DEBIT, - "currency": "GBP", - "sort_code": "445566", - "status": shared.BankAccountStatus.ACTIVE, - }, - "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.CreateBankAccountResponse](../../models/shared/createbankaccountresponse.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 | \*/\* | - -## get_create_model - -The *Get create/update bank account model* endpoint returns the expected data for the request payload when creating and updating a [bank account](https://docs.codat.io/sync-for-expenses-api#/schemas/BankAccount) for a given company and integration. - -[Bank accounts](https://docs.codat.io/sync-for-expenses-api#/schemas/BankAccount) are financial accounts maintained by a bank or other financial institution. - -**Integration-specific behavior** - -See the *response examples* for integration-specific indicative models. - - -### Example Usage: Dynamics 365 Business Central - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.bank_accounts.get_create_model(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - }) - - # Handle response - print(res) - -``` -### Example Usage: Exact (Netherlands) - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.bank_accounts.get_create_model(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - }) - - # Handle response - print(res) - -``` -### Example Usage: Exact (UK) - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.bank_accounts.get_create_model(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - }) - - # Handle response - print(res) - -``` -### Example Usage: FreeAgent - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.bank_accounts.get_create_model(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - }) - - # Handle response - print(res) - -``` -### Example Usage: KashFlow - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.bank_accounts.get_create_model(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - }) - - # Handle response - print(res) - -``` -### Example Usage: QuickBooks Desktop - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.bank_accounts.get_create_model(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - }) - - # Handle response - print(res) - -``` -### Example Usage: QuickBooks Online Sandbox - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.bank_accounts.get_create_model(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - }) - - # Handle response - print(res) - -``` -### Example Usage: Sage Business Cloud Accounting - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.bank_accounts.get_create_model(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - }) - - # Handle response - print(res) - -``` -### Example Usage: Sandbox - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.bank_accounts.get_create_model(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.GetCreateBankAccountsModelRequest](../../models/operations/getcreatebankaccountsmodelrequest.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.PushOption](../../models/shared/pushoption.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | +# BankAccounts + +## Overview + +Create bank accounts and view create bank account options. + +### Available Operations + +* [create](#create) - Create bank account +* [get_create_model](#get_create_model) - Get create bank account model + +## create + +The *Create bank account* endpoint creates a new [bank account](https://docs.codat.io/sync-for-expenses-api#/schemas/BankAccount) for a given company's connection. + +[Bank accounts](https://docs.codat.io/sync-for-expenses-api#/schemas/BankAccount) are financial accounts maintained by a bank or other financial institution. + +**Integration-specific behavior** + +Required data may vary by integration. To see what data to post, first call [Get create/update bank account model](https://docs.codat.io/sync-for-expenses-api#/operations/get-create-update-bankAccounts-model). + +### Example Usage: Malformed query + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.bank_accounts.create(request={ + "bank_account": { + "currency": "GBP", + "modified_date": "2022-10-23T00:00:00Z", + "source_modified_date": "2022-10-23T00:00:00Z", + "status": shared.BankAccountStatus.ACTIVE, + }, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` +### Example Usage: QuickBooks Online + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.bank_accounts.create(request={ + "bank_account": { + "account_name": "GBP Bank Account", + "account_number": "12345678", + "account_type": shared.BankAccountType.DEBIT, + "currency": "GBP", + "status": shared.BankAccountStatus.ACTIVE, + }, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` +### Example Usage: Xero + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.bank_accounts.create(request={ + "bank_account": { + "account_name": "Xero GBP Bank Account", + "account_number": "12345678", + "account_type": shared.BankAccountType.DEBIT, + "currency": "GBP", + "sort_code": "445566", + "status": shared.BankAccountStatus.ACTIVE, + }, + "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.CreateBankAccountResponse](../../models/shared/createbankaccountresponse.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 | \*/\* | + +## get_create_model + +The *Get create/update bank account model* endpoint returns the expected data for the request payload when creating and updating a [bank account](https://docs.codat.io/sync-for-expenses-api#/schemas/BankAccount) for a given company and integration. + +[Bank accounts](https://docs.codat.io/sync-for-expenses-api#/schemas/BankAccount) are financial accounts maintained by a bank or other financial institution. + +**Integration-specific behavior** + +See the *response examples* for integration-specific indicative models. + + +### Example Usage: Dynamics 365 Business Central + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.bank_accounts.get_create_model(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` +### Example Usage: Exact (Netherlands) + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.bank_accounts.get_create_model(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` +### Example Usage: Exact (UK) + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.bank_accounts.get_create_model(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` +### Example Usage: FreeAgent + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.bank_accounts.get_create_model(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` +### Example Usage: KashFlow + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.bank_accounts.get_create_model(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` +### Example Usage: QuickBooks Desktop + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.bank_accounts.get_create_model(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` +### Example Usage: QuickBooks Online Sandbox + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.bank_accounts.get_create_model(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` +### Example Usage: Sage Business Cloud Accounting + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.bank_accounts.get_create_model(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` +### Example Usage: Sandbox + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.bank_accounts.get_create_model(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.GetCreateBankAccountsModelRequest](../../models/operations/getcreatebankaccountsmodelrequest.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.PushOption](../../models/shared/pushoption.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-expenses/docs/sdks/companies/README.md b/sync-for-expenses/docs/sdks/companies/README.md index 42963b2e8..272ba93f0 100644 --- a/sync-for-expenses/docs/sdks/companies/README.md +++ b/sync-for-expenses/docs/sdks/companies/README.md @@ -1,571 +1,567 @@ -# Companies - -## Overview - -Create and manage your SMB users' companies. - -### Available Operations - -* [create](#create) - Create company -* [delete](#delete) - Delete a company -* [get](#get) - Get company -* [list](#list) - List companies -* [replace](#replace) - Replace company -* [update](#update) - Update company - -## create - -Use the *Create company* endpoint to create a new [company](https://docs.codat.io/sync-for-expenses-api#/schemas/Company) that represents your customer in Codat. - -A [company](https://docs.codat.io/sync-for-expenses-api#/schemas/Company) represents a business sharing access to their data. -Each company can have multiple [connections](https://docs.codat.io/sync-for-expenses-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_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.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_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.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_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.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_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.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 | \*/\* | - -## delete - -The *Delete company* endpoint permanently deletes a [company](https://docs.codat.io/sync-for-expenses-api#/schemas/Company), its [connections](https://docs.codat.io/sync-for-expenses-api#/schemas/Connection) and any cached data. This operation is irreversible. - -A [company](https://docs.codat.io/sync-for-expenses-api#/schemas/Company) represents a business sharing access to their data. -Each company can have multiple [connections](https://docs.codat.io/sync-for-expenses-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_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - codat_sync_expenses.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-expenses-api#/schemas/Company) represents a business sharing access to their data. -Each company can have multiple [connections](https://docs.codat.io/sync-for-expenses-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_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.companies.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` -### Example Usage: Simple company - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.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_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.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 | \*/\* | - -## list - -The *List companies* endpoint returns a list of [companies](https://docs.codat.io/sync-for-expenses-api#/schemas/Company) associated to your instances. - -A [company](https://docs.codat.io/sync-for-expenses-api#/schemas/Company) represents a business sharing access to their data. -Each company can have multiple [connections](https://docs.codat.io/sync-for-expenses-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_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.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_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.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 | \*/\* | - -## 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-expenses-api#/schemas/Company) represents a business sharing access to their data. -Each company can have multiple [connections](https://docs.codat.io/sync-for-expenses-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_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.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_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.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_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.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-expenses-api#/schemas/Company) represents a business sharing access to their data. - -### Example Usage: Unauthorized - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.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_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.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_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.companies.update(request={ - "company_update_request": { - "tags": { - "refrence": "new reference", - }, - }, - "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 | +# Companies + +## Overview + +Create and manage your SMB users' companies. + +### Available Operations + +* [create](#create) - Create company +* [delete](#delete) - Delete a company +* [get](#get) - Get company +* [list](#list) - List companies +* [replace](#replace) - Replace company +* [update](#update) - Update company + +## create + +Use the *Create company* endpoint to create a new [company](https://docs.codat.io/sync-for-expenses-api#/schemas/Company) that represents your customer in Codat. + +A [company](https://docs.codat.io/sync-for-expenses-api#/schemas/Company) represents a business sharing access to their data. +Each company can have multiple [connections](https://docs.codat.io/sync-for-expenses-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_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.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_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.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_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.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_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.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 | \*/\* | + +## delete + +The *Delete company* endpoint permanently deletes a [company](https://docs.codat.io/sync-for-expenses-api#/schemas/Company), its [connections](https://docs.codat.io/sync-for-expenses-api#/schemas/Connection) and any cached data. This operation is irreversible. + +A [company](https://docs.codat.io/sync-for-expenses-api#/schemas/Company) represents a business sharing access to their data. +Each company can have multiple [connections](https://docs.codat.io/sync-for-expenses-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_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + codat_sync_expenses.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-expenses-api#/schemas/Company) represents a business sharing access to their data. +Each company can have multiple [connections](https://docs.codat.io/sync-for-expenses-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_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.companies.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` +### Example Usage: Simple company + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.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_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.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 | \*/\* | + +## list + +The *List companies* endpoint returns a list of [companies](https://docs.codat.io/sync-for-expenses-api#/schemas/Company) associated to your instances. + +A [company](https://docs.codat.io/sync-for-expenses-api#/schemas/Company) represents a business sharing access to their data. +Each company can have multiple [connections](https://docs.codat.io/sync-for-expenses-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_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.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_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.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 | \*/\* | + +## 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-expenses-api#/schemas/Company) represents a business sharing access to their data. +Each company can have multiple [connections](https://docs.codat.io/sync-for-expenses-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_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.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_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.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_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.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-expenses-api#/schemas/Company) represents a business sharing access to their data. + +### Example Usage: Unauthorized + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.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_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.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_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.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 | \*/\* | \ No newline at end of file diff --git a/sync-for-expenses/docs/sdks/companyinfo/README.md b/sync-for-expenses/docs/sdks/companyinfo/README.md index d67a192bc..f0254d8a0 100644 --- a/sync-for-expenses/docs/sdks/companyinfo/README.md +++ b/sync-for-expenses/docs/sdks/companyinfo/README.md @@ -1,55 +1,55 @@ -# CompanyInfo - -## Overview - -View the company information of your customers' linked accounting software. - -### Available Operations - -* [get](#get) - Get company info - -## get - -Gets the latest basic info for a company. - -### Example Usage - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.company_info.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | -| `request` | [operations.GetCompanyInfoRequest](../../models/operations/getcompanyinforequest.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 | 401, 402, 403, 404, 409, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | +# CompanyInfo + +## Overview + +View the company information of your customers' linked accounting software. + +### Available Operations + +* [get](#get) - Get company info + +## get + +Gets the latest basic info for a company. + +### Example Usage + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.company_info.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | +| `request` | [operations.GetCompanyInfoRequest](../../models/operations/getcompanyinforequest.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 | 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-expenses/docs/sdks/configuration/README.md b/sync-for-expenses/docs/sdks/configuration/README.md index 59d0ed9bc..163591b5d 100644 --- a/sync-for-expenses/docs/sdks/configuration/README.md +++ b/sync-for-expenses/docs/sdks/configuration/README.md @@ -1,109 +1,107 @@ -# Configuration - -## Overview - -View and manage mapping configuration and defaults for expense transactions. - -### Available Operations - -* [get](#get) - Get company configuration -* [set](#set) - Set company configuration - -## get - -Gets a company's expense sync configuration - -### Example Usage - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.configuration.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | -| `request` | [operations.GetCompanyConfigurationRequest](../../models/operations/getcompanyconfigurationrequest.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.CompanyConfiguration](../../models/shared/companyconfiguration.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 | \*/\* | - -## set - -Sets a company's expense sync configuration - -### Example Usage - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.configuration.set(request={ - "company_configuration": { - "bank_account": { - "id": "32", - }, - "customer": {}, - "supplier": {}, - }, - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | -| `request` | [operations.SetCompanyConfigurationRequest](../../models/operations/setcompanyconfigurationrequest.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.CompanyConfiguration](../../models/shared/companyconfiguration.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ---------------------------- | ---------------------------- | ---------------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | +# ConfigurationApi + +## Overview + +View and manage mapping configuration and defaults for expense transactions. + +### Available Operations + +* [get](#get) - Get company configuration +* [set](#set) - Set company configuration + +## get + +Gets a company's expense sync configuration + +### Example Usage + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.configuration.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | +| `request` | [operations.GetCompanyConfigurationRequest](../../models/operations/getcompanyconfigurationrequest.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.CompanyConfiguration](../../models/shared/companyconfiguration.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 | \*/\* | + +## set + +Sets a company's expense sync configuration + +### Example Usage + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.configuration.set(request={ + "company_configuration": { + "bank_account": { + "id": "32", + }, + }, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | +| `request` | [operations.SetCompanyConfigurationRequest](../../models/operations/setcompanyconfigurationrequest.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.CompanyConfiguration](../../models/shared/companyconfiguration.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-expenses/docs/sdks/connections/README.md b/sync-for-expenses/docs/sdks/connections/README.md index 2068f6abb..2f7624837 100644 --- a/sync-for-expenses/docs/sdks/connections/README.md +++ b/sync-for-expenses/docs/sdks/connections/README.md @@ -1,324 +1,318 @@ -# Connections - -## Overview - -Create new and manage existing data connections for a company. - -### Available Operations - -* [create](#create) - Create connection -* [create_partner_expense_connection](#create_partner_expense_connection) - Create partner expense connection -* [delete](#delete) - Delete connection -* [get](#get) - Get connection -* [list](#list) - List connections -* [unlink](#unlink) - Unlink connection - -## 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_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.connections.create(request={ - "request_body": { - "platform_key": "gbol", - }, - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` -### Example Usage: Unauthorized - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.connections.create(request={ - "request_body": { - "platform_key": "gbol", - }, - "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 | \*/\* | - -## create_partner_expense_connection - -Creates a partner expense data connection - -### Example Usage - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.connections.create_partner_expense_connection(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -| `request` | [operations.CreatePartnerExpenseConnectionRequest](../../models/operations/createpartnerexpenseconnectionrequest.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 | 400, 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_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - codat_sync_expenses.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 | \*/\* | - -## 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_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.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 | \*/\* | - -## list - -List the connections for a company. - -### Example Usage - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.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 | \*/\* | - -## 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_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.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 | +# Connections + +## Overview + +Create new and manage existing data connections for a company. + +### Available Operations + +* [create](#create) - Create connection +* [create_partner_expense_connection](#create_partner_expense_connection) - Create partner expense connection +* [delete](#delete) - Delete connection +* [get](#get) - Get connection +* [list](#list) - List connections +* [unlink](#unlink) - Unlink connection + +## 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_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.connections.create(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` +### Example Usage: Unauthorized + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.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 | \*/\* | + +## create_partner_expense_connection + +Creates a partner expense data connection + +### Example Usage + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.connections.create_partner_expense_connection(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | +| `request` | [operations.CreatePartnerExpenseConnectionRequest](../../models/operations/createpartnerexpenseconnectionrequest.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 | 400, 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_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + codat_sync_expenses.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 | \*/\* | + +## 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_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.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 | \*/\* | + +## list + +List the connections for a company. + +### Example Usage + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.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 | \*/\* | + +## 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_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.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-expenses/docs/sdks/customers/README.md b/sync-for-expenses/docs/sdks/customers/README.md index 32263cfd5..34b983086 100644 --- a/sync-for-expenses/docs/sdks/customers/README.md +++ b/sync-for-expenses/docs/sdks/customers/README.md @@ -1,1054 +1,1035 @@ -# Customers - -## Overview - -Get, create, and update customers. - -### Available Operations - -* [create](#create) - Create customer -* [get](#get) - Get customer -* [list](#list) - List customers -* [update](#update) - Update customer - -## create - -The *Create customer* endpoint creates a new [customer](https://docs.codat.io/sync-for-expenses-api#/schemas/Customer) for a given company's connection. - -[Customers](https://docs.codat.io/sync-for-expenses-api#/schemas/Customer) are people or organizations that buy goods or services from the SMB. - -**Integration-specific behavior** - -Required data may vary by integration. To see what data to post, first call [Get create/update customer model](https://docs.codat.io/sync-for-expenses-api#/operations/get-create-update-customers-model). - -### Example Usage - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.create(request={ - "customer": { - "contacts": [ - { - "modified_date": "2022-10-23T00:00:00Z", - "phone": None, - "status": shared.CustomerStatus.UNKNOWN, - }, - ], - "default_currency": "GBP", - "modified_date": "2022-10-23T00:00:00Z", - "source_modified_date": "2022-10-23T00:00:00Z", - "status": shared.CustomerStatus.UNKNOWN, - }, - "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.CreateCustomerRequest](../../models/operations/createcustomerrequest.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.CreateCustomerResponse](../../models/shared/createcustomerresponse.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 | \*/\* | - -## get - -The *Get customer* endpoint returns a single customer for a given customerId. - -[Customers](https://docs.codat.io/sync-for-expenses-api#/schemas/Customer) are people or organizations that buy goods or services from the SMB. - -Before using this endpoint, you must have [retrieved data for the company](https://docs.codat.io/sync-for-expenses-api#/operations/refresh-company-data). - - -### Example Usage: Clear Books - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: Dynamics 365 Business Central - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: Exact (Netherlands) - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: Exact (UK) - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: FreeAgent - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: FreshBooks - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: KashFlow - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: Oracle NetSuite - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: QuickBooks Desktop - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: QuickBooks Online - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: QuickBooks Online Sandbox - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: Sage 200cloud - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: Sage 50 (UK) - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: Sage Business Cloud Accounting - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: Sage Intacct - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: Wave - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: Xero - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: Zoho Books - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | -| `request` | [operations.GetCustomerRequest](../../models/operations/getcustomerrequest.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.Customer](../../models/shared/customer.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 | \*/\* | - -## list - -The *List customers* endpoint returns a list of [customers](https://docs.codat.io/sync-for-expenses-api#/schemas/Customer) for a given company's connection. - -[Customers](https://docs.codat.io/sync-for-expenses-api#/schemas/Customer) are people or organizations that buy goods or services from the SMB. - -Before using this endpoint, you must have [retrieved data for the company](https://docs.codat.io/sync-for-expenses-api#/operations/refresh-company-data). - - -### Example Usage: Clear Books - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: Dynamics 365 Business Central - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: Exact (Netherlands) - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: Exact (UK) - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: FreeAgent - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: FreshBooks - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: KashFlow - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: Oracle NetSuite - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: QuickBooks Desktop - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: QuickBooks Online - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: QuickBooks Online Sandbox - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: Sage 200cloud - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: Sage 50 (UK) - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: Sage Business Cloud Accounting - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: Sage Intacct - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: Wave - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: Xero - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: Zoho Books - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.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.ListCustomersRequest](../../models/operations/listcustomersrequest.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.Customers](../../models/shared/customers.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 customer* endpoint updates an existing [customer](https://docs.codat.io/sync-for-expenses-api#/schemas/Customer) for a given company's connection. - -[Customers](https://docs.codat.io/sync-for-expenses-api#/schemas/Customer) are people or organizations that buy goods or services from the SMB. - -**Integration-specific behavior** - -Required data may vary by integration. To see what data to post, first call [Get create/update customer model](https://docs.codat.io/sync-for-expenses-api#/operations/get-create-update-customers-model). - -### Example Usage - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.customers.update(request={ - "customer": { - "contacts": [ - { - "modified_date": "2022-10-23T00:00:00Z", - "phone": [ - { - "number": "+44 25691 154789", - "type": shared.Type.PRIMARY, - }, - ], - "status": shared.CustomerStatus.UNKNOWN, - }, - ], - "default_currency": "GBP", - "modified_date": "2022-10-23T00:00:00Z", - "source_modified_date": "2022-10-23T00:00:00Z", - "status": shared.CustomerStatus.ACTIVE, - }, - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | -| `request` | [operations.UpdateCustomerRequest](../../models/operations/updatecustomerrequest.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.UpdateCustomerResponse](../../models/shared/updatecustomerresponse.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ---------------------------- | ---------------------------- | ---------------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | +# Customers + +## Overview + +Get, create, and update customers. + +### Available Operations + +* [create](#create) - Create customer +* [get](#get) - Get customer +* [list](#list) - List customers +* [update](#update) - Update customer + +## create + +The *Create customer* endpoint creates a new [customer](https://docs.codat.io/sync-for-expenses-api#/schemas/Customer) for a given company's connection. + +[Customers](https://docs.codat.io/sync-for-expenses-api#/schemas/Customer) are people or organizations that buy goods or services from the SMB. + +**Integration-specific behavior** + +Required data may vary by integration. To see what data to post, first call [Get create/update customer model](https://docs.codat.io/sync-for-expenses-api#/operations/get-create-update-customers-model). + +### Example Usage + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.create(request={ + "customer": { + "contacts": [], + "default_currency": "GBP", + "modified_date": "2022-10-23T00:00:00Z", + "source_modified_date": "2022-10-23T00:00:00Z", + }, + "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.CreateCustomerRequest](../../models/operations/createcustomerrequest.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.CreateCustomerResponse](../../models/shared/createcustomerresponse.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 | \*/\* | + +## get + +The *Get customer* endpoint returns a single customer for a given customerId. + +[Customers](https://docs.codat.io/sync-for-expenses-api#/schemas/Customer) are people or organizations that buy goods or services from the SMB. + +Before using this endpoint, you must have [retrieved data for the company](https://docs.codat.io/sync-for-expenses-api#/operations/refresh-company-data). + + +### Example Usage: Clear Books + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: Dynamics 365 Business Central + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: Exact (Netherlands) + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: Exact (UK) + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: FreeAgent + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: FreshBooks + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: KashFlow + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: Oracle NetSuite + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: QuickBooks Desktop + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: QuickBooks Online + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: QuickBooks Online Sandbox + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: Sage 200cloud + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: Sage 50 (UK) + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: Sage Business Cloud Accounting + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: Sage Intacct + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: Wave + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: Xero + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: Zoho Books + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | +| `request` | [operations.GetCustomerRequest](../../models/operations/getcustomerrequest.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.Customer](../../models/shared/customer.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 | \*/\* | + +## list + +The *List customers* endpoint returns a list of [customers](https://docs.codat.io/sync-for-expenses-api#/schemas/Customer) for a given company's connection. + +[Customers](https://docs.codat.io/sync-for-expenses-api#/schemas/Customer) are people or organizations that buy goods or services from the SMB. + +Before using this endpoint, you must have [retrieved data for the company](https://docs.codat.io/sync-for-expenses-api#/operations/refresh-company-data). + + +### Example Usage: Clear Books + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: Dynamics 365 Business Central + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: Exact (Netherlands) + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: Exact (UK) + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: FreeAgent + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: FreshBooks + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: KashFlow + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: Oracle NetSuite + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: QuickBooks Desktop + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: QuickBooks Online + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: QuickBooks Online Sandbox + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: Sage 200cloud + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: Sage 50 (UK) + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: Sage Business Cloud Accounting + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: Sage Intacct + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: Wave + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: Xero + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: Zoho Books + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.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.ListCustomersRequest](../../models/operations/listcustomersrequest.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.Customers](../../models/shared/customers.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 customer* endpoint updates an existing [customer](https://docs.codat.io/sync-for-expenses-api#/schemas/Customer) for a given company's connection. + +[Customers](https://docs.codat.io/sync-for-expenses-api#/schemas/Customer) are people or organizations that buy goods or services from the SMB. + +**Integration-specific behavior** + +Required data may vary by integration. To see what data to post, first call [Get create/update customer model](https://docs.codat.io/sync-for-expenses-api#/operations/get-create-update-customers-model). + +### Example Usage + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.customers.update(request={ + "customer": { + "contacts": [], + "default_currency": "GBP", + "modified_date": "2022-10-23T00:00:00Z", + "source_modified_date": "2022-10-23T00:00:00Z", + }, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + "customer_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | +| `request` | [operations.UpdateCustomerRequest](../../models/operations/updatecustomerrequest.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.UpdateCustomerResponse](../../models/shared/updatecustomerresponse.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-expenses/docs/sdks/expenses/README.md b/sync-for-expenses/docs/sdks/expenses/README.md index 7d6df159a..db03809c4 100644 --- a/sync-for-expenses/docs/sdks/expenses/README.md +++ b/sync-for-expenses/docs/sdks/expenses/README.md @@ -1,446 +1,264 @@ -# Expenses - -## Overview - -Create and update transactions that represent your customers' spend. - -### Available Operations - -* [create](#create) - Create expense transaction -* [update](#update) - Update expense transactions - -## create - -The *Create expense* endpoint creates an [expense transaction](https://docs.codat.io/sync-for-expenses-api#/schemas/ExpenseTransaction) in the accounting software for a given company's connection. - -[Expense transactions](https://docs.codat.io/sync-for-expenses-api#/schemas/ExpenseTransaction) represent transactions made with a company debit or credit card. - -### Supported Integrations - -| Integration | Supported | -|-------------------------------|-----------| -| Dynamics 365 Business Central | Yes | -| FreeAgent | Yes | -| QuickBooks Desktop | Yes | -| QuickBooks Online | Yes | -| Oracle NetSuite | Yes | -| Sage Intacct | Yes | -| Xero | Yes | -| Zoho Books | Yes | - - -### Example Usage: Example 1 - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared -from decimal import Decimal - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.expenses.create(request={ - "request_body": [ - { - "bank_account_ref": { - "id": "97", - }, - "contact_ref": { - "id": "430", - }, - "currency": "GBP", - "currency_rate": Decimal("1"), - "id": "a44135b0-6882-489a-83fe-a0c57a4afb19", - "issue_date": "2024-05-21T00:00:00+00:00", - "lines": [ - shared.ExpenseTransactionLine( - account_ref=shared.RecordRef( - id="35", - ), - invoice_to=shared.InvoiceTo( - id="504", - type=shared.InvoiceToType.CUSTOMER, - ), - net_amount=Decimal("100"), - tax_amount=Decimal("20"), - tax_rate_ref=shared.RecordRef( - id="23_Bills", - ), - tracking_refs=[ - shared.TrackingRef( - id="DEPARTMENT_3", - ), - shared.TrackingRef(), - ], - ), - ], - "merchant_name": "Amazon UK", - "notes": "amazon purchase", - "type": shared.ExpenseTransactionType.PAYMENT, - }, - ], - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` -### Example Usage: Malformed query - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared -from decimal import Decimal - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.expenses.create(request={ - "request_body": [ - { - "bank_account_ref": { - "id": "97", - }, - "contact_ref": { - "id": "430", - }, - "currency": "GBP", - "currency_rate": Decimal("1"), - "id": "a44135b0-6882-489a-83fe-a0c57a4afb19", - "issue_date": "2024-05-21T00:00:00+00:00", - "lines": [ - shared.ExpenseTransactionLine( - account_ref=shared.RecordRef( - id="35", - ), - invoice_to=shared.InvoiceTo( - id="504", - type=shared.InvoiceToType.CUSTOMER, - ), - net_amount=Decimal("100"), - tax_amount=Decimal("20"), - tax_rate_ref=shared.RecordRef( - id="23_Bills", - ), - tracking_refs=[ - shared.TrackingRef( - id="DEPARTMENT_3", - ), - shared.TrackingRef(), - ], - ), - ], - "merchant_name": "Amazon UK", - "notes": "amazon purchase", - "type": shared.ExpenseTransactionType.PAYMENT, - }, - ], - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` -### Example Usage: Payment - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared -from decimal import Decimal - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.expenses.create(request={ - "request_body": [ - { - "bank_account_ref": { - "id": "97", - }, - "contact_ref": { - "id": "430", - }, - "currency": "GBP", - "currency_rate": Decimal("1"), - "id": "4d7c6929-7770-412b-91bb-44d3bc71d111", - "issue_date": "2024-05-21T00:00:00+00:00", - "lines": [ - shared.ExpenseTransactionLine( - account_ref=shared.RecordRef( - id="35", - ), - invoice_to=shared.InvoiceTo( - id="504", - type=shared.InvoiceToType.CUSTOMER, - ), - net_amount=Decimal("100"), - tax_amount=Decimal("20"), - tax_rate_ref=shared.RecordRef( - id="23_Bills", - ), - tracking_refs=[ - shared.TrackingRef( - id="DEPARTMENT_5", - ), - ], - ), - ], - "merchant_name": "Amazon UK", - "notes": "APPLE.COM/BILL - 09001077498 - Card Ending: 4590", - "type": shared.ExpenseTransactionType.PAYMENT, - }, - ], - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` -### Example Usage: Refund - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared -from decimal import Decimal - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.expenses.create(request={ - "request_body": [ - { - "bank_account_ref": { - "id": "97", - }, - "contact_ref": { - "id": "430", - }, - "currency": "GBP", - "id": "7008d3f2-aeb4-11ed-afa1-0242ac120002", - "issue_date": "2024-02-17T00:00:00+00:00", - "lines": [ - shared.ExpenseTransactionLine( - account_ref=shared.RecordRef( - id="42", - ), - net_amount=Decimal("100"), - tax_amount=Decimal("20"), - tax_rate_ref=shared.RecordRef( - id="23_Bills", - ), - tracking_refs=[ - shared.TrackingRef( - id="DEPARTMENT_6", - ), - ], - ), - ], - "merchant_name": "Amazon UK", - "notes": "APPLE.COM/BILL - 09001077498 - Card Ending: 4590", - "type": shared.ExpenseTransactionType.REFUND, - }, - ], - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | -| `request` | [operations.CreateExpenseTransactionRequest](../../models/operations/createexpensetransactionrequest.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.CreateExpenseResponse](../../models/shared/createexpenseresponse.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 expense* endpoint updates an existing [expense transaction](https://docs.codat.io/sync-for-expenses-api#/schemas/UpdateExpenseRequest) in the accounting software for a given company's connection. - -[Expense transactions](https://docs.codat.io/sync-for-expenses-api#/schemas/UpdateExpenseRequest) represent transactions made with a company debit or credit card. - -### Supported integrations -The following integrations are supported for the [Payment](https://docs.codat.io/expenses/sync-process/expense-transactions#transaction-types) transaction `type` only: -| Integration | Supported | -|-----------------------|-----------| -| FreeAgent | Yes | -| QuickBooks Desktop | Yes | -| QuickBooks Online | Yes | -| Oracle NetSuite | Yes | -| Sage Intacct | Yes | -| Xero | Yes | -| Zoho Books | Yes | - -#### Integration-specific behavior - -| Integration | Specifics | -|-----------------------|-----------| -| Sage Intacct | To sync **debit card expenses**, map the debit card to a Credit Card with the account type set to `Debit`.| - -### Example Usage: Malformed query - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared -from decimal import Decimal - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.expenses.update(request={ - "update_expense_request": { - "bank_account_ref": { - "id": "787dfb37-5707-4dc0-8a86-8d74e4cc78ea", - }, - "contact_ref": { - "id": "40e3e57c-2322-4898-966c-ca41adfd23fd", - }, - "currency": "GBP", - "issue_date": "2022-06-28T00:00:00.000Z", - "lines": [ - shared.ExpenseTransactionLine( - account_ref=shared.RecordRef( - id="40e3e57c-2322-4898-966c-ca41adfd23fd", - ), - invoice_to=None, - item_ref=None, - net_amount=Decimal("100"), - tax_amount=Decimal("20"), - tax_rate_ref=shared.RecordRef( - id="40e3e57c-2322-4898-966c-ca41adfd23fd", - ), - tracking_refs=None, - ), - ], - "merchant_name": "Amazon UK", - "notes": "APPLE.COM/BILL - 09001077498 - Card Ending: 4590", - "type": shared.UpdateExpenseRequestType.PAYMENT, - }, - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "transaction_id": "336694d8-2dca-4cb5-a28d-3ccb83e55eee", - }) - - # Handle response - print(res) - -``` -### Example Usage: Payment - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared -from decimal import Decimal - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.expenses.update(request={ - "update_expense_request": { - "bank_account_ref": { - "id": "97", - }, - "contact_ref": { - "id": "430", - }, - "currency": "GBP", - "currency_rate": Decimal("1"), - "issue_date": "2024-05-21T00:00:00+00:00", - "lines": [ - shared.ExpenseTransactionLine( - account_ref=shared.RecordRef( - id="35", - ), - invoice_to=shared.InvoiceTo( - id="504", - type=shared.InvoiceToType.CUSTOMER, - ), - net_amount=Decimal("100"), - tax_amount=Decimal("20"), - tax_rate_ref=shared.RecordRef( - id="23_Bills", - ), - tracking_refs=[ - shared.TrackingRef( - id="DEPARTMENT_5", - ), - ], - ), - ], - "merchant_name": "Amazon UK", - "notes": "APPLE.COM/BILL - 09001077498 - Card Ending: 4590", - "type": shared.UpdateExpenseRequestType.PAYMENT, - }, - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "transaction_id": "336694d8-2dca-4cb5-a28d-3ccb83e55eee", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | -| `request` | [operations.UpdateExpenseTransactionRequest](../../models/operations/updateexpensetransactionrequest.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.UpdateExpenseResponse](../../models/shared/updateexpenseresponse.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| --------------------------------- | --------------------------------- | --------------------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 404, 422, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | +# Expenses + +## Overview + +Create and update transactions that represent your customers' spend. + +### Available Operations + +* [create](#create) - Create expense transaction +* [update](#update) - Update expense transactions + +## create + +The *Create expense* endpoint creates an [expense transaction](https://docs.codat.io/sync-for-expenses-api#/schemas/ExpenseTransaction) in the accounting software for a given company's connection. + +[Expense transactions](https://docs.codat.io/sync-for-expenses-api#/schemas/ExpenseTransaction) represent transactions made with a company debit or credit card. + +### Supported Integrations + +| Integration | Supported | +|-------------------------------|-----------| +| Dynamics 365 Business Central | Yes | +| FreeAgent | Yes | +| QuickBooks Desktop | Yes | +| QuickBooks Online | Yes | +| Oracle NetSuite | Yes | +| Sage Intacct | Yes | +| Xero | Yes | +| Zoho Books | Yes | + + +### Example Usage: Example 1 + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.expenses.create(request={ + "request_body": [], + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` +### Example Usage: Malformed query + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.expenses.create(request={ + "request_body": [], + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` +### Example Usage: Payment + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.expenses.create(request={ + "request_body": [], + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` +### Example Usage: Refund + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.expenses.create(request={ + "request_body": [], + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | +| `request` | [operations.CreateExpenseTransactionRequest](../../models/operations/createexpensetransactionrequest.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.CreateExpenseResponse](../../models/shared/createexpenseresponse.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 expense* endpoint updates an existing [expense transaction](https://docs.codat.io/sync-for-expenses-api#/schemas/UpdateExpenseRequest) in the accounting software for a given company's connection. + +[Expense transactions](https://docs.codat.io/sync-for-expenses-api#/schemas/UpdateExpenseRequest) represent transactions made with a company debit or credit card. + +### Supported integrations +The following integrations are supported for the [Payment](https://docs.codat.io/expenses/sync-process/expense-transactions#transaction-types) transaction `type` only: +| Integration | Supported | +|-----------------------|-----------| +| FreeAgent | Yes | +| QuickBooks Desktop | Yes | +| QuickBooks Online | Yes | +| Oracle NetSuite | Yes | +| Sage Intacct | Yes | +| Xero | Yes | +| Zoho Books | Yes | + +#### Integration-specific behavior + +| Integration | Specifics | +|-----------------------|-----------| +| Sage Intacct | To sync **debit card expenses**, map the debit card to a Credit Card with the account type set to `Debit`.| + +### Example Usage: Malformed query + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.expenses.update(request={ + "update_expense_request": { + "bank_account_ref": { + "id": "787dfb37-5707-4dc0-8a86-8d74e4cc78ea", + }, + "contact_ref": { + "id": "40e3e57c-2322-4898-966c-ca41adfd23fd", + "type": shared.ExpenseContactRefType.SUPPLIER, + }, + "currency": "GBP", + "issue_date": "2022-06-28T00:00:00.000Z", + "lines": [], + "merchant_name": "Amazon UK", + "notes": "APPLE.COM/BILL - 09001077498 - Card Ending: 4590", + "type": shared.UpdateExpenseRequestType.PAYMENT, + }, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "transaction_id": "336694d8-2dca-4cb5-a28d-3ccb83e55eee", + }) + + # Handle response + print(res) + +``` +### Example Usage: Payment + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared +from decimal import Decimal + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.expenses.update(request={ + "update_expense_request": { + "bank_account_ref": { + "id": "97", + }, + "contact_ref": { + "id": "430", + "type": shared.ExpenseContactRefType.SUPPLIER, + }, + "currency": "GBP", + "currency_rate": Decimal("1"), + "issue_date": "2024-05-21T00:00:00+00:00", + "lines": [], + "merchant_name": "Amazon UK", + "notes": "APPLE.COM/BILL - 09001077498 - Card Ending: 4590", + "type": shared.UpdateExpenseRequestType.PAYMENT, + }, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "transaction_id": "336694d8-2dca-4cb5-a28d-3ccb83e55eee", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | +| `request` | [operations.UpdateExpenseTransactionRequest](../../models/operations/updateexpensetransactionrequest.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.UpdateExpenseResponse](../../models/shared/updateexpenseresponse.md)** + +### Errors + +| Error Type | Status Code | Content Type | +| --------------------------------- | --------------------------------- | --------------------------------- | +| errors.ErrorMessage | 400, 401, 402, 403, 404, 422, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | | errors.SDKError | 4XX, 5XX | \*/\* | \ No newline at end of file diff --git a/sync-for-expenses/docs/sdks/managedata/README.md b/sync-for-expenses/docs/sdks/managedata/README.md index 5bd5f931b..1aa00ea19 100644 --- a/sync-for-expenses/docs/sdks/managedata/README.md +++ b/sync-for-expenses/docs/sdks/managedata/README.md @@ -1,248 +1,247 @@ -# ManageData - -## Overview - -Control and monitor the retrieval of data from an integration. - -### Available Operations - -* [get](#get) - Get data status -* [get_pull_operation](#get_pull_operation) - Get pull operation -* [list_pull_operations](#list_pull_operations) - List pull operations -* [refresh_all_data_types](#refresh_all_data_types) - Refresh all data -* [refresh_data_type](#refresh_data_type) - Refresh data type - -## get - -Get the state of each data type for a company - -### Example Usage - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.manage_data.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | -| `request` | [operations.GetDataStatusRequest](../../models/operations/getdatastatusrequest.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 - -**[operations.GetDataStatusDataStatuses](../../models/operations/getdatastatusdatastatuses.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_pull_operation - -Retrieve information about a single dataset or pull operation. - -### Example Usage - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.manage_data.get_pull_operation(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "dataset_id": "fa5f3e86-bd80-49b8-853c-5fbba4b201f5", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | -| `request` | [operations.GetPullOperationRequest](../../models/operations/getpulloperationrequest.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.PullOperation](../../models/shared/pulloperation.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 | \*/\* | - -## list_pull_operations - -Gets the pull operation history (datasets) for a given company. - -### Example Usage - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.manage_data.list_pull_operations(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.ListPullOperationsRequest](../../models/operations/listpulloperationsrequest.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.PullOperations](../../models/shared/pulloperations.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 | \*/\* | - -## refresh_all_data_types - -Refreshes all data types with `fetch on first link` set to `true` for a given company. - -This is an asynchronous operation, and will bring updated data into Codat from the linked integration for you to view. - -[Read more](https://docs.codat.io/core-concepts/data-type-settings) about data type settings and `fetch on first link`. - -### Example Usage - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - codat_sync_expenses.manage_data.refresh_all_data_types(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Use the SDK ... - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | -| `request` | [operations.RefreshAllDataTypesRequest](../../models/operations/refreshalldatatypesrequest.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 | 400, 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## refresh_data_type - -Refreshes a given data type for a given company. - -This is an asynchronous operation, and will bring updated data into Codat from the linked integration for you to view. - -### Example Usage - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.manage_data.refresh_data_type(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "data_type": shared.SchemaDataType.INVOICES, - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -| `request` | [operations.RefreshDataTypeRequest](../../models/operations/refreshdatatyperequest.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.PullOperation](../../models/shared/pulloperation.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ---------------------------- | ---------------------------- | ---------------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | +# ManageData + +## Overview + +Control and monitor the retrieval of data from an integration. + +### Available Operations + +* [get](#get) - Get data status +* [get_pull_operation](#get_pull_operation) - Get pull operation +* [list_pull_operations](#list_pull_operations) - List pull operations +* [refresh_all_data_types](#refresh_all_data_types) - Refresh all data +* [refresh_data_type](#refresh_data_type) - Refresh data type + +## get + +Get the state of each data type for a company + +### Example Usage + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.manage_data.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | +| `request` | [operations.GetDataStatusRequest](../../models/operations/getdatastatusrequest.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 + +**[operations.GetDataStatusDataStatuses](../../models/operations/getdatastatusdatastatuses.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_pull_operation + +Retrieve information about a single dataset or pull operation. + +### Example Usage + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.manage_data.get_pull_operation(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| `request` | [operations.GetPullOperationRequest](../../models/operations/getpulloperationrequest.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.PullOperation](../../models/shared/pulloperation.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 | \*/\* | + +## list_pull_operations + +Gets the pull operation history (datasets) for a given company. + +### Example Usage + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.manage_data.list_pull_operations(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.ListPullOperationsRequest](../../models/operations/listpulloperationsrequest.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.PullOperations](../../models/shared/pulloperations.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 | \*/\* | + +## refresh_all_data_types + +Refreshes all data types with `fetch on first link` set to `true` for a given company. + +This is an asynchronous operation, and will bring updated data into Codat from the linked integration for you to view. + +[Read more](https://docs.codat.io/core-concepts/data-type-settings) about data type settings and `fetch on first link`. + +### Example Usage + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + codat_sync_expenses.manage_data.refresh_all_data_types(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Use the SDK ... + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | +| `request` | [operations.RefreshAllDataTypesRequest](../../models/operations/refreshalldatatypesrequest.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 | 400, 401, 402, 403, 404, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## refresh_data_type + +Refreshes a given data type for a given company. + +This is an asynchronous operation, and will bring updated data into Codat from the linked integration for you to view. + +### Example Usage + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.manage_data.refresh_data_type(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "data_type": shared.SchemaDataType.INVOICES, + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | +| `request` | [operations.RefreshDataTypeRequest](../../models/operations/refreshdatatyperequest.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.PullOperation](../../models/shared/pulloperation.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-expenses/docs/sdks/mappingoptions/README.md b/sync-for-expenses/docs/sdks/mappingoptions/README.md index 202c82e69..6bfe463ba 100644 --- a/sync-for-expenses/docs/sdks/mappingoptions/README.md +++ b/sync-for-expenses/docs/sdks/mappingoptions/README.md @@ -1,55 +1,55 @@ -# MappingOptions - -## Overview - -Get accounts, trackingCategories and taxRates that can be used in your create and update requests. - -### Available Operations - -* [get_mapping_options](#get_mapping_options) - Mapping options - -## get_mapping_options - -Gets the mapping options (accounts, trackingCategories and taxRates) for a company's accounting software - -### Example Usage - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.mapping_options.get_mapping_options(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | -| `request` | [operations.GetMappingOptionsRequest](../../models/operations/getmappingoptionsrequest.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.MappingOptions](../../models/shared/mappingoptions.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | +# MappingOptions + +## Overview + +Get accounts, trackingCategories and taxRates that can be used in your create and update requests. + +### Available Operations + +* [get_mapping_options](#get_mapping_options) - Mapping options + +## get_mapping_options + +Gets the mapping options (accounts, trackingCategories and taxRates) for a company's accounting software + +### Example Usage + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.mapping_options.get_mapping_options(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | +| `request` | [operations.GetMappingOptionsRequest](../../models/operations/getmappingoptionsrequest.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.MappingOptions](../../models/shared/mappingoptions.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-expenses/docs/sdks/pushoperations/README.md b/sync-for-expenses/docs/sdks/pushoperations/README.md index febd1fb5d..9c96d1bc3 100644 --- a/sync-for-expenses/docs/sdks/pushoperations/README.md +++ b/sync-for-expenses/docs/sdks/pushoperations/README.md @@ -1,105 +1,104 @@ -# PushOperations - -## Overview - -View historic push operations. - -### Available Operations - -* [get](#get) - Get push operation -* [list](#list) - List push operations - -## get - -Retrieve push operation. - -### Example Usage - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.push_operations.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "push_operation_key": "660e8684-c0fb-4468-9e2a-b2e3b115d747", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | -| `request` | [operations.GetPushOperationRequest](../../models/operations/getpushoperationrequest.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.PushOperation](../../models/shared/pushoperation.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 | \*/\* | - -## list - -List push operation records. - -### Example Usage - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.push_operations.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.ListPushOperationsRequest](../../models/operations/listpushoperationsrequest.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.PushOperations](../../models/shared/pushoperations.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ---------------------------- | ---------------------------- | ---------------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | +# PushOperations + +## Overview + +View historic push operations. + +### Available Operations + +* [get](#get) - Get push operation +* [list](#list) - List push operations + +## get + +Retrieve push operation. + +### Example Usage + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.push_operations.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| `request` | [operations.GetPushOperationRequest](../../models/operations/getpushoperationrequest.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.PushOperation](../../models/shared/pushoperation.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 | \*/\* | + +## list + +List push operation records. + +### Example Usage + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.push_operations.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.ListPushOperationsRequest](../../models/operations/listpushoperationsrequest.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.PushOperations](../../models/shared/pushoperations.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-expenses/docs/sdks/reimbursements/README.md b/sync-for-expenses/docs/sdks/reimbursements/README.md index ac787414c..f0c96225d 100644 --- a/sync-for-expenses/docs/sdks/reimbursements/README.md +++ b/sync-for-expenses/docs/sdks/reimbursements/README.md @@ -1,442 +1,220 @@ -# Reimbursements - -## Overview - -Create and update transactions that represent your customers' repayable spend. - -### Available Operations - -* [create](#create) - Create reimbursable expense transaction -* [update](#update) - Update reimbursable expense transaction - -## create - -Use the *Create reimbursable expense* endpoint to submit an employee expense claim in the accounting platform for a given company's connection. - -[Reimbursable expense requests](https://docs.codat.io/sync-for-expenses-api#/schemas/ReimbursableExpenseTransactionRequest) are reflected in the accounting software in the form of **Bills** against an employee (who exists as a supplier in the accounting platform). - -### Supported Integrations -| Integration | Supported | -|-----------------------|-----------| -| FreeAgent | Yes | -| QuickBooks Desktop | Yes | -| QuickBooks Online | Yes | -| Oracle NetSuite | Yes | -| Zoho Books | Yes | -| Sage Intacct | Yes | - -### Example Usage: Create reimbursable expense - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared -from decimal import Decimal - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.reimbursements.create(request={ - "request_body": [ - { - "contact_ref": { - "id": "752", - }, - "currency": "GBP", - "currency_rate": Decimal("1"), - "due_date": "2024-05-21", - "id": "4d7c6929-7770-412b-91bb-44d3bc71d111", - "issue_date": "2024-05-21", - "lines": [ - shared.ReimbursableExpenseTransactionLine( - account_ref=shared.RecordRef( - id="35", - ), - description="Hotel", - invoice_to=shared.InvoiceTo( - id="504", - type=shared.InvoiceToType.CUSTOMER, - ), - net_amount=Decimal("100"), - tax_amount=Decimal("20"), - tax_rate_ref=shared.RecordRef( - id="23_Bills", - ), - tracking_refs=[ - shared.TrackingRef( - id="DEPARTMENT_5", - ), - ], - ), - ], - "notes": "APPLE.COM/BILL - 09001077498 - Card Ending: 4590", - "reference": "expenses w/c 01/07", - }, - ], - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` -### Example Usage: Example 1 - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared -from decimal import Decimal - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.reimbursements.create(request={ - "request_body": [ - { - "ap_account_ref": None, - "contact_ref": { - "id": "40e3e57c-2322-4898-966c-ca41adfd23fd", - }, - "currency": "GBP", - "due_date": "2022-10-23T00:00:00Z", - "id": "4d7c6929-7770-412b-91bb-44d3bc71d111", - "issue_date": "2022-10-23T00:00:00Z", - "lines": [ - shared.ReimbursableExpenseTransactionLine( - account_ref=shared.RecordRef( - id="40e3e57c-2322-4898-966c-ca41adfd23fd", - ), - description="2-night hotel stay", - invoice_to=shared.InvoiceTo( - id="80000002-1674552702", - type=shared.InvoiceToType.CUSTOMER, - ), - item_ref=shared.ItemRef( - id="80000002-1675158984", - ), - net_amount=Decimal("100"), - tax_amount=Decimal("20"), - tax_rate_ref=shared.RecordRef( - id="40e3e57c-2322-4898-966c-ca41adfd23fd", - ), - tracking_refs=[ - shared.TrackingRef( - id="e9a1b63d-9ff0-40e7-8038-016354b987e6", - ), - ], - ), - ], - "notes": "APPLE.COM/BILL - 09001077498 - Card Ending: 4590", - }, - ], - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` -### Example Usage: Malformed query - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared -from decimal import Decimal - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.reimbursements.create(request={ - "request_body": [ - { - "ap_account_ref": None, - "contact_ref": { - "id": "40e3e57c-2322-4898-966c-ca41adfd23fd", - }, - "currency": "GBP", - "due_date": "2022-10-23T00:00:00Z", - "id": "4d7c6929-7770-412b-91bb-44d3bc71d111", - "issue_date": "2022-10-23T00:00:00Z", - "lines": [ - shared.ReimbursableExpenseTransactionLine( - account_ref=shared.RecordRef( - id="40e3e57c-2322-4898-966c-ca41adfd23fd", - ), - description="2-night hotel stay", - invoice_to=shared.InvoiceTo( - id="80000002-1674552702", - type=shared.InvoiceToType.CUSTOMER, - ), - item_ref=shared.ItemRef( - id="80000002-1675158984", - ), - net_amount=Decimal("100"), - tax_amount=Decimal("20"), - tax_rate_ref=shared.RecordRef( - id="40e3e57c-2322-4898-966c-ca41adfd23fd", - ), - tracking_refs=[ - shared.TrackingRef( - id="e9a1b63d-9ff0-40e7-8038-016354b987e6", - ), - ], - ), - ], - "notes": "APPLE.COM/BILL - 09001077498 - Card Ending: 4590", - }, - ], - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| -------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | -| `request` | [operations.CreateReimbursableExpenseTransactionRequest](../../models/operations/createreimbursableexpensetransactionrequest.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.CreateReimbursableExpenseResponse](../../models/shared/createreimbursableexpenseresponse.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 reimbursable expense* endpoint updates an existing employee expense claim in the accounting platform for a given company's connection. - -Updating an existing [reimbursable expense transaction](https://docs.codat.io/sync-for-expenses-api#/schemas/UpdateReimbursableExpenseTransactionRequest) will update the existing **bill** against an employee (who exists as a supplier in the accounting software). - -### Supported Integrations -| Integration | Supported | -|-----------------------|-----------| -| FreeAgent | Yes | -| QuickBooks Online | Yes | -| Oracle NetSuite | Yes | -| Zoho Books | Yes | - - - -### Example Usage: Example 1 - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared -from decimal import Decimal - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.reimbursements.update(request={ - "update_reimbursable_expense_transaction_request": { - "ap_account_ref": { - "id": "8000004C-1724173136", - }, - "contact_ref": { - "id": "40e3e57c-2322-4898-966c-ca41adfd23fd", - }, - "currency": "GBP", - "due_date": "2022-10-23T00:00:00Z", - "issue_date": "2022-10-23T00:00:00Z", - "lines": [ - shared.ReimbursableExpenseTransactionLine( - account_ref=shared.RecordRef( - id="40e3e57c-2322-4898-966c-ca41adfd23fd", - ), - description="2-night hotel stay", - invoice_to=shared.InvoiceTo( - id="80000002-1674552702", - type=shared.InvoiceToType.CUSTOMER, - ), - item_ref=shared.ItemRef( - id="80000002-1675158984", - ), - net_amount=Decimal("100"), - tax_amount=Decimal("20"), - tax_rate_ref=shared.RecordRef( - id="40e3e57c-2322-4898-966c-ca41adfd23fd", - ), - tracking_refs=[ - shared.TrackingRef( - id="e9a1b63d-9ff0-40e7-8038-016354b987e6", - ), - ], - ), - ], - "notes": "APPLE.COM/BILL - 09001077498 - Card Ending: 4590", - }, - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "transaction_id": "336694d8-2dca-4cb5-a28d-3ccb83e55eee", - }) - - # Handle response - print(res) - -``` -### Example Usage: Malformed query - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared -from decimal import Decimal - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.reimbursements.update(request={ - "update_reimbursable_expense_transaction_request": { - "ap_account_ref": { - "id": "8000004C-1724173136", - }, - "contact_ref": { - "id": "40e3e57c-2322-4898-966c-ca41adfd23fd", - }, - "currency": "GBP", - "due_date": "2022-10-23T00:00:00Z", - "issue_date": "2022-10-23T00:00:00Z", - "lines": [ - shared.ReimbursableExpenseTransactionLine( - account_ref=shared.RecordRef( - id="40e3e57c-2322-4898-966c-ca41adfd23fd", - ), - description="2-night hotel stay", - invoice_to=shared.InvoiceTo( - id="80000002-1674552702", - type=shared.InvoiceToType.CUSTOMER, - ), - item_ref=shared.ItemRef( - id="80000002-1675158984", - ), - net_amount=Decimal("100"), - tax_amount=Decimal("20"), - tax_rate_ref=shared.RecordRef( - id="40e3e57c-2322-4898-966c-ca41adfd23fd", - ), - tracking_refs=[ - shared.TrackingRef( - id="e9a1b63d-9ff0-40e7-8038-016354b987e6", - ), - ], - ), - ], - "notes": "APPLE.COM/BILL - 09001077498 - Card Ending: 4590", - }, - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "transaction_id": "336694d8-2dca-4cb5-a28d-3ccb83e55eee", - }) - - # Handle response - print(res) - -``` -### Example Usage: Update reimbursable expense - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared -from decimal import Decimal - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.reimbursements.update(request={ - "update_reimbursable_expense_transaction_request": { - "contact_ref": { - "id": "752", - }, - "currency": "GBP", - "currency_rate": Decimal("1"), - "due_date": "2024-05-21", - "issue_date": "2024-05-21", - "lines": [ - shared.ReimbursableExpenseTransactionLine( - account_ref=shared.RecordRef( - id="35", - ), - description="Hotel", - invoice_to=shared.InvoiceTo( - id="504", - type=shared.InvoiceToType.CUSTOMER, - ), - net_amount=Decimal("100"), - tax_amount=Decimal("20"), - tax_rate_ref=shared.RecordRef( - id="23_Bills", - ), - tracking_refs=[ - shared.TrackingRef( - id="DEPARTMENT_5", - ), - ], - ), - ], - "notes": "APPLE.COM/BILL - 09001077498 - Card Ending: 4590", - "reference": "expenses w/c 01/07", - }, - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "transaction_id": "336694d8-2dca-4cb5-a28d-3ccb83e55eee", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| -------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | -| `request` | [operations.UpdateReimbursableExpenseTransactionRequest](../../models/operations/updatereimbursableexpensetransactionrequest.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.CreateReimbursableExpenseResponse](../../models/shared/createreimbursableexpenseresponse.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ---------------------------- | ---------------------------- | ---------------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | +# Reimbursements + +## Overview + +Create and update transactions that represent your customers' repayable spend. + +### Available Operations + +* [create](#create) - Create reimbursable expense transaction +* [update](#update) - Update reimbursable expense transaction + +## create + +Use the *Create reimbursable expense* endpoint to submit an employee expense claim in the accounting platform for a given company's connection. + +[Reimbursable expense requests](https://docs.codat.io/sync-for-expenses-api#/schemas/ReimbursableExpenseTransactionRequest) are reflected in the accounting software in the form of **Bills** against an employee (who exists as a supplier in the accounting platform). + +### Supported Integrations +| Integration | Supported | +|-----------------------|-----------| +| FreeAgent | Yes | +| QuickBooks Desktop | Yes | +| QuickBooks Online | Yes | +| Oracle NetSuite | Yes | +| Zoho Books | Yes | +| Sage Intacct | Yes | + +### Example Usage: Create reimbursable expense + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.reimbursements.create(request={ + "request_body": [], + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` +### Example Usage: Example 1 + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.reimbursements.create(request={ + "request_body": [], + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` +### Example Usage: Malformed query + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.reimbursements.create(request={ + "request_body": [], + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| -------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | +| `request` | [operations.CreateReimbursableExpenseTransactionRequest](../../models/operations/createreimbursableexpensetransactionrequest.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.CreateReimbursableExpenseResponse](../../models/shared/createreimbursableexpenseresponse.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 reimbursable expense* endpoint updates an existing employee expense claim in the accounting platform for a given company's connection. + +Updating an existing [reimbursable expense transaction](https://docs.codat.io/sync-for-expenses-api#/schemas/UpdateReimbursableExpenseTransactionRequest) will update the existing **bill** against an employee (who exists as a supplier in the accounting software). + +### Supported Integrations +| Integration | Supported | +|-----------------------|-----------| +| FreeAgent | Yes | +| QuickBooks Online | Yes | +| Oracle NetSuite | Yes | +| Zoho Books | Yes | + + + +### Example Usage: Example 1 + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.reimbursements.update(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "transaction_id": "336694d8-2dca-4cb5-a28d-3ccb83e55eee", + }) + + # Handle response + print(res) + +``` +### Example Usage: Malformed query + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.reimbursements.update(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "transaction_id": "336694d8-2dca-4cb5-a28d-3ccb83e55eee", + }) + + # Handle response + print(res) + +``` +### Example Usage: Update reimbursable expense + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.reimbursements.update(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "transaction_id": "336694d8-2dca-4cb5-a28d-3ccb83e55eee", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| -------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | +| `request` | [operations.UpdateReimbursableExpenseTransactionRequest](../../models/operations/updatereimbursableexpensetransactionrequest.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.CreateReimbursableExpenseResponse](../../models/shared/createreimbursableexpenseresponse.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-expenses/docs/sdks/suppliers/README.md b/sync-for-expenses/docs/sdks/suppliers/README.md index 807668a7d..9c54e47d1 100644 --- a/sync-for-expenses/docs/sdks/suppliers/README.md +++ b/sync-for-expenses/docs/sdks/suppliers/README.md @@ -1,1177 +1,1137 @@ -# Suppliers - -## Overview - -Get, create, and update suppliers. - -### Available Operations - -* [create](#create) - Create supplier -* [get](#get) - Get supplier -* [list](#list) - List suppliers -* [update](#update) - Update supplier - -## create - -The *Create supplier* endpoint creates a new [supplier](https://docs.codat.io/sync-for-expenses-api#/schemas/Supplier) for a given company's connection. - -[Suppliers](https://docs.codat.io/sync-for-expenses-api#/schemas/Supplier) are people or organizations that provide something, such as a product or service. - -**Integration-specific behavior** - -Required data may vary by integration. To see what data to post, first call [Get create/update supplier model](https://docs.codat.io/sync-for-expenses-api#/operations/get-create-update-suppliers-model). - -### Supported Integrations - -| Integration | Supported | -|-------------------------------|-----------| -| Dynamics 365 Business Central | Yes | -| FreeAgent | Yes | -| Oracle NetSuite | Yes | -| QuickBooks Desktop | Yes | -| QuickBooks Online | Yes | -| Sage Intacct | Yes | -| Xero | Yes | -| Zoho Books | Yes | - - -### Example Usage: Malformed query - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.create(request={ - "supplier": { - "addresses": [ - { - "city": "Bakersfield", - "country": "USA", - "line1": "Unit 51", - "line2": "Bakersfield Industrial Estate", - "region": "California", - "type": shared.AccountingAddressType.BILLING, - }, - ], - "contact_name": "Kelly's Industrial Supplies", - "default_currency": "string", - "email_address": "sales@kellysupplies.com", - "id": "C520FFD4-F6F6-4FC2-A6D2-5D7088B2B14F", - "metadata": { - "is_deleted": True, - }, - "modified_date": "2022-10-23T00:00:00Z", - "phone": "07999 999999", - "registration_number": "string", - "source_modified_date": "2022-10-23T00:00:00Z", - "status": shared.SupplierStatus.UNKNOWN, - "supplemental_data": { - "content": { - "property1": { - "property1": "", - "property2": "", - }, - "property2": { - "property1": "", - "property2": "", - }, - }, - }, - "supplier_name": "Kelly's Industrial Supplies", - "tax_number": "string", - }, - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", - }) - - # Handle response - print(res) - -``` -### Example Usage: Sage Intacct - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.create(request={ - "supplier": { - "contact_name": "Joe Bloggs", - "id": "73593", - "status": shared.SupplierStatus.ACTIVE, - "supplier_name": "test 20230420 1004", - }, - "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.CreateSupplierResponse](../../models/shared/createsupplierresponse.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 | \*/\* | - -## get - -The *Get supplier* endpoint returns a single supplier for a given supplierId. - -[Suppliers](https://docs.codat.io/sync-for-expenses-api#/schemas/Supplier) are people or organizations that provide something, such as a product or service. - -Before using this endpoint, you must have [retrieved data for the company](https://docs.codat.io/sync-for-expenses-api#/operations/refresh-all-data-types). - -### Supported Integrations - -| Integration | Supported | -|-------------------------------|-----------| -| Dynamics 365 Business Central | Yes | -| FreeAgent | Yes | -| Oracle NetSuite | Yes | -| QuickBooks Desktop | Yes | -| QuickBooks Online | Yes | -| Sage Intacct | Yes | -| Xero | Yes | -| Zoho Books | Yes | - - -### Example Usage: Clear Books - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: Dynamics 365 Business Central - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: Exact (Netherlands) - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: Exact (UK) - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: FreeAgent - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: FreshBooks - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: KashFlow - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: Oracle NetSuite - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: QuickBooks Desktop - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: QuickBooks Online - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: QuickBooks Online Sandbox - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: Sage 200cloud - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: Sage 50 (UK) - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: Sage Business Cloud Accounting - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: Sage Intacct - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: Wave - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: Xero - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` -### Example Usage: Zoho Books - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | -| `request` | [operations.GetSupplierRequest](../../models/operations/getsupplierrequest.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 | 401, 402, 403, 404, 409, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | -| errors.SDKError | 4XX, 5XX | \*/\* | - -## list - -The *List suppliers* endpoint returns a list of [suppliers](https://docs.codat.io/sync-for-expenses-api#/schemas/Supplier) for a given company's connection. - -[Suppliers](https://docs.codat.io/sync-for-expenses-api#/schemas/Supplier) are people or organizations that provide something, such as a product or service. - -Before using this endpoint, you must have [retrieved data for the company](https://docs.codat.io/sync-for-expenses-api#/operations/refresh-all-data-types). - -### Supported Integrations - -| Integration | Supported | -|-------------------------------|-----------| -| Dynamics 365 Business Central | Yes | -| FreeAgent | Yes | -| Oracle NetSuite | Yes | -| QuickBooks Desktop | Yes | -| QuickBooks Online | Yes | -| Sage Intacct | Yes | -| Xero | Yes | -| Zoho Books | Yes | - - -### Example Usage: Clear Books - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: Dynamics 365 Business Central - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: Exact (Netherlands) - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: Exact (UK) - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: FreeAgent - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: FreshBooks - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: KashFlow - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: Oracle NetSuite - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: QuickBooks Desktop - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: QuickBooks Online - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: QuickBooks Online Sandbox - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: Sage 200cloud - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: Sage 50 (UK) - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: Sage Business Cloud Accounting - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: Sage Intacct - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: Wave - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: Xero - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "order_by": "-modifiedDate", - "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", - }) - - # Handle response - print(res) - -``` -### Example Usage: Zoho Books - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.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.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 | \*/\* | - -## update - -The *Update supplier* endpoint updates an existing [supplier](https://docs.codat.io/sync-for-expenses-api#/schemas/Supplier) for a given company's connection. - -[Suppliers](https://docs.codat.io/sync-for-expenses-api#/schemas/Supplier) are people or organizations that provide something, such as a product or service. - -**Integration-specific behavior** - -Required data may vary by integration. To see what data to post, first call [Get create/update supplier model](https://docs.codat.io/sync-for-expenses-api#/operations/get-create-update-suppliers-model). - -### Supported Integrations - -| Integration | Supported | -|-------------------|-----------| -| FreeAgent | Yes | -| QuickBooks Online | Yes | -| Xero | Yes | - - -### Example Usage - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.suppliers.update(request={ - "supplier": { - "addresses": [ - { - "city": "Bakersfield", - "country": "USA", - "line1": "Unit 51", - "line2": "Bakersfield Industrial Estate", - "region": "California", - "type": shared.AccountingAddressType.BILLING, - }, - ], - "contact_name": "Kelly's Industrial Supplies", - "default_currency": "string", - "email_address": "sales@kellysupplies.com", - "id": "C520FFD4-F6F6-4FC2-A6D2-5D7088B2B14F", - "metadata": { - "is_deleted": True, - }, - "modified_date": "2022-10-23T00:00:00Z", - "phone": "07999 999999", - "registration_number": "string", - "source_modified_date": "2022-10-23T00:00:00Z", - "status": shared.SupplierStatus.UNKNOWN, - "supplemental_data": { - "content": { - "property1": { - "property1": "", - "property2": "", - }, - "property2": { - "property1": "", - "property2": "", - }, - }, - }, - "supplier_name": "Kelly's Industrial Supplies", - "tax_number": "string", - }, - "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.UpdateSupplierResponse](../../models/shared/updatesupplierresponse.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 + +* [create](#create) - Create supplier +* [get](#get) - Get supplier +* [list](#list) - List suppliers +* [update](#update) - Update supplier + +## create + +The *Create supplier* endpoint creates a new [supplier](https://docs.codat.io/sync-for-expenses-api#/schemas/Supplier) for a given company's connection. + +[Suppliers](https://docs.codat.io/sync-for-expenses-api#/schemas/Supplier) are people or organizations that provide something, such as a product or service. + +**Integration-specific behavior** + +Required data may vary by integration. To see what data to post, first call [Get create/update supplier model](https://docs.codat.io/sync-for-expenses-api#/operations/get-create-update-suppliers-model). + +### Supported Integrations + +| Integration | Supported | +|-------------------------------|-----------| +| Dynamics 365 Business Central | Yes | +| FreeAgent | Yes | +| Oracle NetSuite | Yes | +| QuickBooks Desktop | Yes | +| QuickBooks Online | Yes | +| Sage Intacct | Yes | +| Xero | Yes | +| Zoho Books | Yes | + + +### Example Usage: Malformed query + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.create(request={ + "supplier": { + "addresses": [], + "contact_name": "Kelly's Industrial Supplies", + "default_currency": "string", + "email_address": "sales@kellysupplies.com", + "id": "C520FFD4-F6F6-4FC2-A6D2-5D7088B2B14F", + "metadata": { + "is_deleted": True, + }, + "modified_date": "2022-10-23T00:00:00Z", + "phone": "07999 999999", + "registration_number": "string", + "source_modified_date": "2022-10-23T00:00:00Z", + "status": shared.SupplierStatus.UNKNOWN, + "supplemental_data": {}, + "supplier_name": "Kelly's Industrial Supplies", + "tax_number": "string", + }, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "connection_id": "2e9d2c44-f675-40ba-8049-353bfcb5e171", + }) + + # Handle response + print(res) + +``` +### Example Usage: Sage Intacct + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.create(request={ + "supplier": { + "contact_name": "Joe Bloggs", + "id": "73593", + "status": shared.SupplierStatus.ACTIVE, + "supplier_name": "test 20230420 1004", + }, + "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.CreateSupplierResponse](../../models/shared/createsupplierresponse.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 | \*/\* | + +## get + +The *Get supplier* endpoint returns a single supplier for a given supplierId. + +[Suppliers](https://docs.codat.io/sync-for-expenses-api#/schemas/Supplier) are people or organizations that provide something, such as a product or service. + +Before using this endpoint, you must have [retrieved data for the company](https://docs.codat.io/sync-for-expenses-api#/operations/refresh-all-data-types). + +### Supported Integrations + +| Integration | Supported | +|-------------------------------|-----------| +| Dynamics 365 Business Central | Yes | +| FreeAgent | Yes | +| Oracle NetSuite | Yes | +| QuickBooks Desktop | Yes | +| QuickBooks Online | Yes | +| Sage Intacct | Yes | +| Xero | Yes | +| Zoho Books | Yes | + + +### Example Usage: Clear Books + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: Dynamics 365 Business Central + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: Exact (Netherlands) + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: Exact (UK) + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: FreeAgent + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: FreshBooks + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: KashFlow + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: Oracle NetSuite + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: QuickBooks Desktop + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: QuickBooks Online + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: QuickBooks Online Sandbox + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: Sage 200cloud + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: Sage 50 (UK) + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: Sage Business Cloud Accounting + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: Sage Intacct + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: Wave + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: Xero + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` +### Example Usage: Zoho Books + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "supplier_id": "13d946f0-c5d5-42bc-b092-97ece17923ab", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | +| `request` | [operations.GetSupplierRequest](../../models/operations/getsupplierrequest.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 | 401, 402, 403, 404, 409, 429 | application/json | +| errors.ErrorMessage | 500, 503 | application/json | +| errors.SDKError | 4XX, 5XX | \*/\* | + +## list + +The *List suppliers* endpoint returns a list of [suppliers](https://docs.codat.io/sync-for-expenses-api#/schemas/Supplier) for a given company's connection. + +[Suppliers](https://docs.codat.io/sync-for-expenses-api#/schemas/Supplier) are people or organizations that provide something, such as a product or service. + +Before using this endpoint, you must have [retrieved data for the company](https://docs.codat.io/sync-for-expenses-api#/operations/refresh-all-data-types). + +### Supported Integrations + +| Integration | Supported | +|-------------------------------|-----------| +| Dynamics 365 Business Central | Yes | +| FreeAgent | Yes | +| Oracle NetSuite | Yes | +| QuickBooks Desktop | Yes | +| QuickBooks Online | Yes | +| Sage Intacct | Yes | +| Xero | Yes | +| Zoho Books | Yes | + + +### Example Usage: Clear Books + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: Dynamics 365 Business Central + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: Exact (Netherlands) + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: Exact (UK) + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: FreeAgent + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: FreshBooks + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: KashFlow + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: Oracle NetSuite + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: QuickBooks Desktop + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: QuickBooks Online + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: QuickBooks Online Sandbox + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: Sage 200cloud + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: Sage 50 (UK) + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: Sage Business Cloud Accounting + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: Sage Intacct + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: Wave + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: Xero + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "order_by": "-modifiedDate", + "query": "id=e3334455-1aed-4e71-ab43-6bccf12092ee", + }) + + # Handle response + print(res) + +``` +### Example Usage: Zoho Books + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.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.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 | \*/\* | + +## update + +The *Update supplier* endpoint updates an existing [supplier](https://docs.codat.io/sync-for-expenses-api#/schemas/Supplier) for a given company's connection. + +[Suppliers](https://docs.codat.io/sync-for-expenses-api#/schemas/Supplier) are people or organizations that provide something, such as a product or service. + +**Integration-specific behavior** + +Required data may vary by integration. To see what data to post, first call [Get create/update supplier model](https://docs.codat.io/sync-for-expenses-api#/operations/get-create-update-suppliers-model). + +### Supported Integrations + +| Integration | Supported | +|-------------------|-----------| +| FreeAgent | Yes | +| QuickBooks Online | Yes | +| Xero | Yes | + + +### Example Usage + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.suppliers.update(request={ + "supplier": { + "addresses": [], + "contact_name": "Kelly's Industrial Supplies", + "default_currency": "string", + "email_address": "sales@kellysupplies.com", + "id": "C520FFD4-F6F6-4FC2-A6D2-5D7088B2B14F", + "metadata": { + "is_deleted": True, + }, + "modified_date": "2022-10-23T00:00:00Z", + "phone": "07999 999999", + "registration_number": "string", + "source_modified_date": "2022-10-23T00:00:00Z", + "status": shared.SupplierStatus.UNKNOWN, + "supplemental_data": {}, + "supplier_name": "Kelly's Industrial Supplies", + "tax_number": "string", + }, + "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.UpdateSupplierResponse](../../models/shared/updatesupplierresponse.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-expenses/docs/sdks/sync/README.md b/sync-for-expenses/docs/sdks/sync/README.md index 49bde36bf..d77251b1d 100644 --- a/sync-for-expenses/docs/sdks/sync/README.md +++ b/sync-for-expenses/docs/sdks/sync/README.md @@ -1,197 +1,197 @@ -# Sync - -## Overview - -Monitor the status of data syncs. - -### Available Operations - -* [get](#get) - Get sync status -* [get_last_successful_sync](#get_last_successful_sync) - Last successful sync -* [get_latest_sync](#get_latest_sync) - Latest sync status -* [list](#list) - List sync statuses - -## get - -Get the sync status for a specified sync - -### Example Usage - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.sync.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "sync_id": "6fb40d5e-b13e-11ed-afa1-0242ac120002", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | -| `request` | [operations.GetSyncByIDRequest](../../models/operations/getsyncbyidrequest.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.CompanySyncStatus](../../models/shared/companysyncstatus.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_last_successful_sync - -Gets the status of the last successful sync - -### Example Usage - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.sync.get_last_successful_sync(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -| `request` | [operations.GetLastSuccessfulSyncRequest](../../models/operations/getlastsuccessfulsyncrequest.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.CompanySyncStatus](../../models/shared/companysyncstatus.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_latest_sync - -Gets the latest sync status - -### Example Usage - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.sync.get_latest_sync(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | -| `request` | [operations.GetLatestSyncRequest](../../models/operations/getlatestsyncrequest.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.CompanySyncStatus](../../models/shared/companysyncstatus.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 | \*/\* | - -## list - -Gets a list of sync statuses - -### Example Usage - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.sync.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| -------------------------------------------------------------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------------- | -| `request` | [operations.ListSyncsRequest](../../models/operations/listsyncsrequest.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.CompanySyncStatus]](../../models/.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ----------------------- | ----------------------- | ----------------------- | -| errors.ErrorMessage | 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | +# Sync + +## Overview + +Monitor the status of data syncs. + +### Available Operations + +* [get](#get) - Get sync status +* [get_last_successful_sync](#get_last_successful_sync) - Last successful sync +* [get_latest_sync](#get_latest_sync) - Latest sync status +* [list](#list) - List sync statuses + +## get + +Get the sync status for a specified sync + +### Example Usage + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.sync.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "sync_id": "6fb40d5e-b13e-11ed-afa1-0242ac120002", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | +| `request` | [operations.GetSyncByIDRequest](../../models/operations/getsyncbyidrequest.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.CompanySyncStatus](../../models/shared/companysyncstatus.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_last_successful_sync + +Gets the status of the last successful sync + +### Example Usage + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.sync.get_last_successful_sync(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | +| `request` | [operations.GetLastSuccessfulSyncRequest](../../models/operations/getlastsuccessfulsyncrequest.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.CompanySyncStatus](../../models/shared/companysyncstatus.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_latest_sync + +Gets the latest sync status + +### Example Usage + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.sync.get_latest_sync(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | +| `request` | [operations.GetLatestSyncRequest](../../models/operations/getlatestsyncrequest.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.CompanySyncStatus](../../models/shared/companysyncstatus.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 | \*/\* | + +## list + +Gets a list of sync statuses + +### Example Usage + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.sync.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| -------------------------------------------------------------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------------- | +| `request` | [operations.ListSyncsRequest](../../models/operations/listsyncsrequest.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.CompanySyncStatus]](../../models/.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-expenses/docs/sdks/transactionstatus/README.md b/sync-for-expenses/docs/sdks/transactionstatus/README.md index 67c89f430..b24ceca25 100644 --- a/sync-for-expenses/docs/sdks/transactionstatus/README.md +++ b/sync-for-expenses/docs/sdks/transactionstatus/README.md @@ -1,105 +1,105 @@ -# TransactionStatus - -## Overview - -Monitor the status of individual transactions in data syncs. - -### Available Operations - -* [get](#get) - Get sync transaction -* [list](#list) - List sync transactions - -## get - -Gets the status of a transaction for a sync - -### Example Usage - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.transaction_status.get(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "sync_id": "6fb40d5e-b13e-11ed-afa1-0242ac120002", - "transaction_id": "336694d8-2dca-4cb5-a28d-3ccb83e55eee", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -| `request` | [operations.GetSyncTransactionRequest](../../models/operations/getsynctransactionrequest.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.SchemaTransaction]](../../models/.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 | \*/\* | - -## list - -Gets the transactions and status for a sync - -### Example Usage - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.transaction_status.list(request={ - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "sync_id": "6fb40d5e-b13e-11ed-afa1-0242ac120002", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | -| `request` | [operations.ListSyncTransactionsRequest](../../models/operations/listsynctransactionsrequest.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.Transactions](../../models/shared/transactions.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ---------------------------- | ---------------------------- | ---------------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | +# TransactionStatus + +## Overview + +Monitor the status of individual transactions in data syncs. + +### Available Operations + +* [get](#get) - Get sync transaction +* [list](#list) - List sync transactions + +## get + +Gets the status of a transaction for a sync + +### Example Usage + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.transaction_status.get(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "sync_id": "6fb40d5e-b13e-11ed-afa1-0242ac120002", + "transaction_id": "336694d8-2dca-4cb5-a28d-3ccb83e55eee", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | +| `request` | [operations.GetSyncTransactionRequest](../../models/operations/getsynctransactionrequest.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.SchemaTransaction]](../../models/.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 | \*/\* | + +## list + +Gets the transactions and status for a sync + +### Example Usage + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.transaction_status.list(request={ + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "sync_id": "6fb40d5e-b13e-11ed-afa1-0242ac120002", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | +| `request` | [operations.ListSyncTransactionsRequest](../../models/operations/listsynctransactionsrequest.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.Transactions](../../models/shared/transactions.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-expenses/docs/sdks/transfers/README.md b/sync-for-expenses/docs/sdks/transfers/README.md index 402381ba3..160514a48 100644 --- a/sync-for-expenses/docs/sdks/transfers/README.md +++ b/sync-for-expenses/docs/sdks/transfers/README.md @@ -1,169 +1,143 @@ -# Transfers - -## Overview - -Create and update transactions that represent the movement of your customers' money. - -### Available Operations - -* [create](#create) - Create transfer transaction - -## create - -Use the *Create transfer* endpoint to create or update a [transfer transaction](https://docs.codat.io/sync-for-expenses-api#/schemas/TransferTransactionRequest) in the accounting software for a given company's connection. - -Transfers record the movement of money between two bank accounts, or between a bank account and a nominal account. Use them to represent actions such as topping up a debit card account or a balance transfer to another credit card. - -The `from.amount` and `to.amount` fields are in the native currency of the account. - -### Supported Integrations -| Integration | Create transfer | Update transfer | -|-----------------------|------------------|------------------| -| Dynamics | No | No | -| FreeAgent | Yes | Yes | -| NetSuite | No | No | -| QuickBooks Desktop | Yes | No | -| QuickBooks Online | Yes | Yes | -| Sage Intacct | No | No | -| Xero | Yes | No | -| Zoho Books | No | No | - -### Example Usage: Create transfer - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared -from decimal import Decimal - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.transfers.create(request={ - "transfer_transaction_request": { - "date_": "2021-05-21T00:00:00+00:00", - "description": "Sample transfer description", - "from_": { - "account_ref": { - "id": "787dfb37-5707-4dc0-8a86-8d74e4cc78ea", - }, - "amount": Decimal("100"), - }, - "to": { - "account_ref": { - "id": "777dfb37-5506-3dc0-6g86-8d34z4cc78ea", - }, - "amount": Decimal("100"), - }, - }, - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "transaction_id": "336694d8-2dca-4cb5-a28d-3ccb83e55eee", - }) - - # Handle response - print(res) - -``` -### Example Usage: Example 1 - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared -from decimal import Decimal - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.transfers.create(request={ - "transfer_transaction_request": { - "date_": "2022-10-23T00:00:00Z", - "description": "Transfer from bank account Y to bank account Z", - "from_": { - "account_ref": { - "id": "", - }, - "amount": Decimal("7329.18"), - }, - "to": { - "account_ref": { - "id": "", - }, - "amount": Decimal("522.15"), - }, - }, - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "transaction_id": "336694d8-2dca-4cb5-a28d-3ccb83e55eee", - }) - - # Handle response - print(res) - -``` -### Example Usage: Malformed query - - -```python -from codat_sync_for_expenses import CodatSyncExpenses -from codat_sync_for_expenses.models import shared -from decimal import Decimal - - -with CodatSyncExpenses( - security=shared.Security( - auth_header="Basic BASE_64_ENCODED(API_KEY)", - ), -) as codat_sync_expenses: - - res = codat_sync_expenses.transfers.create(request={ - "transfer_transaction_request": { - "date_": "2022-10-23T00:00:00Z", - "description": "Transfer from bank account Y to bank account Z", - "from_": { - "account_ref": { - "id": "", - }, - "amount": Decimal("7329.18"), - }, - "to": { - "account_ref": { - "id": "", - }, - "amount": Decimal("522.15"), - }, - }, - "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", - "transaction_id": "336694d8-2dca-4cb5-a28d-3ccb83e55eee", - }) - - # Handle response - print(res) - -``` - -### Parameters - -| Parameter | Type | Required | Description | -| ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | -| `request` | [operations.CreateTransferTransactionRequest](../../models/operations/createtransfertransactionrequest.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.TransferTransactionResponse](../../models/shared/transfertransactionresponse.md)** - -### Errors - -| Error Type | Status Code | Content Type | -| ---------------------------- | ---------------------------- | ---------------------------- | -| errors.ErrorMessage | 400, 401, 402, 403, 404, 429 | application/json | -| errors.ErrorMessage | 500, 503 | application/json | +# Transfers + +## Overview + +Create and update transactions that represent the movement of your customers' money. + +### Available Operations + +* [create](#create) - Create transfer transaction + +## create + +Use the *Create transfer* endpoint to create or update a [transfer transaction](https://docs.codat.io/sync-for-expenses-api#/schemas/TransferTransactionRequest) in the accounting software for a given company's connection. + +Transfers record the movement of money between two bank accounts, or between a bank account and a nominal account. Use them to represent actions such as topping up a debit card account or a balance transfer to another credit card. + +The `from.amount` and `to.amount` fields are in the native currency of the account. + +### Supported Integrations +| Integration | Create transfer | Update transfer | +|-----------------------|------------------|------------------| +| Dynamics | No | No | +| FreeAgent | Yes | Yes | +| NetSuite | No | No | +| QuickBooks Desktop | Yes | No | +| QuickBooks Online | Yes | Yes | +| Sage Intacct | No | No | +| Xero | Yes | No | +| Zoho Books | No | No | + +### Example Usage: Create transfer + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared +from decimal import Decimal + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.transfers.create(request={ + "transfer_transaction_request": { + "date_": "2021-05-21T00:00:00+00:00", + "description": "Sample transfer description", + "from_": { + "account_ref": { + "id": "787dfb37-5707-4dc0-8a86-8d74e4cc78ea", + }, + "amount": Decimal("100"), + }, + "to": { + "account_ref": { + "id": "777dfb37-5506-3dc0-6g86-8d34z4cc78ea", + }, + "amount": Decimal("100"), + }, + }, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "transaction_id": "336694d8-2dca-4cb5-a28d-3ccb83e55eee", + }) + + # Handle response + print(res) + +``` +### Example Usage: Example 1 + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.transfers.create(request={ + "transfer_transaction_request": { + "date_": "2022-10-23T00:00:00Z", + "description": "Transfer from bank account Y to bank account Z", + }, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "transaction_id": "336694d8-2dca-4cb5-a28d-3ccb83e55eee", + }) + + # Handle response + print(res) + +``` +### Example Usage: Malformed query + + +```python +from codat_sync_for_expenses import CodatSyncExpenses +from codat_sync_for_expenses.models import shared + + +with CodatSyncExpenses( + security=shared.Security( + auth_header="Basic BASE_64_ENCODED(API_KEY)", + ), +) as codat_sync_expenses: + + res = codat_sync_expenses.transfers.create(request={ + "transfer_transaction_request": { + "date_": "2022-10-23T00:00:00Z", + "description": "Transfer from bank account Y to bank account Z", + }, + "company_id": "8a210b68-6988-11ed-a1eb-0242ac120002", + "transaction_id": "336694d8-2dca-4cb5-a28d-3ccb83e55eee", + }) + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | +| `request` | [operations.CreateTransferTransactionRequest](../../models/operations/createtransfertransactionrequest.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.TransferTransactionResponse](../../models/shared/transfertransactionresponse.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-expenses/pyproject.toml b/sync-for-expenses/pyproject.toml index abdbe034c..c1f22dde5 100644 --- a/sync-for-expenses/pyproject.toml +++ b/sync-for-expenses/pyproject.toml @@ -1,58 +1,35 @@ - [project] name = "codat-sync-for-expenses" -version = "8.0.1" +version = "8.0.2" description = "Push expenses to accounting software." -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_expenses", from = "src" } + { include = "codat_sync_for_expenses", from = "src" }, ] -include = ["py.typed", "src/codat_sync_for_expenses/py.typed"] - -[tool.setuptools.package-data] -"*" = ["py.typed", "src/codat_sync_for_expenses/py.typed"] - -[virtualenvs] -in-project = true +include = ["src/codat_sync_for_expenses/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-expenses/src/codat_sync_for_expenses/__init__.py b/sync-for-expenses/src/codat_sync_for_expenses/__init__.py index 833c68cd5..0efe287b8 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/__init__.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/__init__.py @@ -1,4 +1,181 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +# flake8: noqa + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.api.accounts import Accounts +from codat_sync_for_expenses.api.adjustments import Adjustments +from codat_sync_for_expenses.api.attachments import Attachments +from codat_sync_for_expenses.api.bank_accounts import BankAccounts +from codat_sync_for_expenses.api.companies import Companies +from codat_sync_for_expenses.api.company_info import CompanyInfo +from codat_sync_for_expenses.api.configuration import Configuration +from codat_sync_for_expenses.api.connections import Connections +from codat_sync_for_expenses.api.customers import Customers +from codat_sync_for_expenses.api.expenses import Expenses +from codat_sync_for_expenses.api.manage_data import ManageData +from codat_sync_for_expenses.api.mapping_options import MappingOptions +from codat_sync_for_expenses.api.push_operations import PushOperations +from codat_sync_for_expenses.api.reimbursements import Reimbursements +from codat_sync_for_expenses.api.suppliers import Suppliers +from codat_sync_for_expenses.api.sync import Sync +from codat_sync_for_expenses.api.transaction_status import TransactionStatus +from codat_sync_for_expenses.api.transfers import Transfers + +# import ApiClient +from codat_sync_for_expenses.api_response import ApiResponse +from codat_sync_for_expenses.api_client import ApiClient +from codat_sync_for_expenses.configuration import Configuration +from codat_sync_for_expenses.exceptions import OpenApiException +from codat_sync_for_expenses.exceptions import ApiTypeError +from codat_sync_for_expenses.exceptions import ApiValueError +from codat_sync_for_expenses.exceptions import ApiKeyError +from codat_sync_for_expenses.exceptions import ApiAttributeError +from codat_sync_for_expenses.exceptions import ApiException + +# import models into sdk package +from codat_sync_for_expenses.models.account import Account +from codat_sync_for_expenses.models.shared.accountmappinginfo import AccountMappingInfo +from codat_sync_for_expenses.models.shared.accountprototype import AccountPrototype +from codat_sync_for_expenses.models.account_reference import AccountReference +from codat_sync_for_expenses.models.account_reference1 import AccountReference1 +from codat_sync_for_expenses.models.shared.accountstatus import AccountStatus +from codat_sync_for_expenses.models.shared.accounttype import AccountType +from codat_sync_for_expenses.models.accounting_address import AccountingAddress +from codat_sync_for_expenses.models.shared.accountingaddresstype import AccountingAddressType +from codat_sync_for_expenses.models.shared.adjustmenttransactionline import AdjustmentTransactionLine +from codat_sync_for_expenses.models.shared.adjustmenttransactionrequest import AdjustmentTransactionRequest +from codat_sync_for_expenses.models.shared.adjustmenttransactionresponse import AdjustmentTransactionResponse +from codat_sync_for_expenses.models.shared.apaccountref import ApAccountRef +from codat_sync_for_expenses.models.shared.attachment import Attachment +from codat_sync_for_expenses.models.shared.bankaccount import BankAccount +from codat_sync_for_expenses.models.shared.bankaccountdetails import BankAccountDetails +from codat_sync_for_expenses.models.bank_account_prototype import BankAccountPrototype +from codat_sync_for_expenses.models.bank_account_reference import BankAccountReference +from codat_sync_for_expenses.models.shared.bankaccountstatus import BankAccountStatus +from codat_sync_for_expenses.models.shared.clientratelimitwebhook import ClientRateLimitWebhook +from codat_sync_for_expenses.models.shared.clientratelimitwebhookpayload import ClientRateLimitWebhookPayload +from codat_sync_for_expenses.models.shared.companies import Companies +from codat_sync_for_expenses.models.shared.company import Company +from codat_sync_for_expenses.models.shared.companyconfiguration import CompanyConfiguration +from codat_sync_for_expenses.models.company_details import CompanyDetails +from codat_sync_for_expenses.models.company_information import CompanyInformation +from codat_sync_for_expenses.models.shared.companyreference import CompanyReference +from codat_sync_for_expenses.models.company_reference_links import CompanyReferenceLinks +from codat_sync_for_expenses.models.shared.companyrequestbody import CompanyRequestBody +from codat_sync_for_expenses.models.shared.companysyncstatus import CompanySyncStatus +from codat_sync_for_expenses.models.shared.companyupdaterequest import CompanyUpdateRequest +from codat_sync_for_expenses.models.shared.connection import Connection +from codat_sync_for_expenses.models.shared.connections import Connections +from codat_sync_for_expenses.models.shared.contact import Contact +from codat_sync_for_expenses.models.shared.createaccountresponse import CreateAccountResponse +from codat_sync_for_expenses.models.create_account_response_all_of_data import CreateAccountResponseAllOfData +from codat_sync_for_expenses.models.create_bank_account_response import CreateBankAccountResponse +from codat_sync_for_expenses.models.create_bank_account_response_all_of_data import CreateBankAccountResponseAllOfData +from codat_sync_for_expenses.models.create_connection_request import CreateConnectionRequest +from codat_sync_for_expenses.models.shared.createcustomerresponse import CreateCustomerResponse +from codat_sync_for_expenses.models.create_customer_response_all_of_data import CreateCustomerResponseAllOfData +from codat_sync_for_expenses.models.shared.createexpenseresponse import CreateExpenseResponse +from codat_sync_for_expenses.models.shared.createreimbursableexpenseresponse import CreateReimbursableExpenseResponse +from codat_sync_for_expenses.models.shared.createsupplierresponse import CreateSupplierResponse +from codat_sync_for_expenses.models.create_supplier_response_all_of_data import CreateSupplierResponseAllOfData +from codat_sync_for_expenses.models.shared.customer import Customer +from codat_sync_for_expenses.models.shared.customerdetails import CustomerDetails +from codat_sync_for_expenses.models.shared.customerstatus import CustomerStatus +from codat_sync_for_expenses.models.shared.customers import Customers +from codat_sync_for_expenses.models.shared.dataconnectionerror import DataConnectionError +from codat_sync_for_expenses.models.shared.dataconnectionstatus import DataConnectionStatus +from codat_sync_for_expenses.models.shared.datastatus import DataStatus +from codat_sync_for_expenses.models.data_statuses import DataStatuses +from codat_sync_for_expenses.models.shared.datatype import DataType +from codat_sync_for_expenses.models.error_message import ErrorMessage +from codat_sync_for_expenses.models.shared.errorvalidation import ErrorValidation +from codat_sync_for_expenses.models.shared.errorvalidationitem import ErrorValidationItem +from codat_sync_for_expenses.models.expense_contact_ref import ExpenseContactRef +from codat_sync_for_expenses.models.shared.expensetransaction import ExpenseTransaction +from codat_sync_for_expenses.models.shared.expensetransactionline import ExpenseTransactionLine +from codat_sync_for_expenses.models.shared.expensessyncwebhook import ExpensesSyncWebhook +from codat_sync_for_expenses.models.shared.expensessyncwebhookpayload import ExpensesSyncWebhookPayload +from codat_sync_for_expenses.models.shared.halref import HalRef +from codat_sync_for_expenses.models.shared.integrationtype import IntegrationType +from codat_sync_for_expenses.models.shared.invoiceto import InvoiceTo +from codat_sync_for_expenses.models.shared.itemref import ItemRef +from codat_sync_for_expenses.models.shared.items import Items +from codat_sync_for_expenses.models.shared.links import Links +from codat_sync_for_expenses.models.shared.mappingoptions import MappingOptions +from codat_sync_for_expenses.models.shared.metadata import Metadata +from codat_sync_for_expenses.models.model3 import Model3 +from codat_sync_for_expenses.models.paging_info import PagingInfo +from codat_sync_for_expenses.models.shared.phonenumber_items import PhoneNumberItems +from codat_sync_for_expenses.models.shared.pulloperation import PullOperation +from codat_sync_for_expenses.models.shared.pulloperations import PullOperations +from codat_sync_for_expenses.models.shared.pushchangetype import PushChangeType +from codat_sync_for_expenses.models.shared.pushfieldvalidation import PushFieldValidation +from codat_sync_for_expenses.models.shared.pushoperation import PushOperation +from codat_sync_for_expenses.models.shared.pushoperationchange import PushOperationChange +from codat_sync_for_expenses.models.shared.pushoperationref import PushOperationRef +from codat_sync_for_expenses.models.shared.pushoperationstatus import PushOperationStatus +from codat_sync_for_expenses.models.shared.pushoperations import PushOperations +from codat_sync_for_expenses.models.shared.pushoption import PushOption +from codat_sync_for_expenses.models.shared.pushoptionchoice import PushOptionChoice +from codat_sync_for_expenses.models.shared.pushoptionproperty import PushOptionProperty +from codat_sync_for_expenses.models.shared.pushoptiontype import PushOptionType +from codat_sync_for_expenses.models.shared.pushvalidationinfo import PushValidationInfo +from codat_sync_for_expenses.models.shared.recordref import RecordRef +from codat_sync_for_expenses.models.shared.reimbursableexpensetransaction import ReimbursableExpenseTransaction +from codat_sync_for_expenses.models.shared.reimbursableexpensetransactionline import ReimbursableExpenseTransactionLine +from codat_sync_for_expenses.models.shared.reimbursementcontactref import ReimbursementContactRef +from codat_sync_for_expenses.models.shared.schema_transaction import SchemaTransaction +from codat_sync_for_expenses.models.shared.status import Status +from codat_sync_for_expenses.models.shared.supplementaldata import SupplementalData +from codat_sync_for_expenses.models.shared.supplier import Supplier +from codat_sync_for_expenses.models.shared.supplierdetails import SupplierDetails +from codat_sync_for_expenses.models.shared.supplierstatus import SupplierStatus +from codat_sync_for_expenses.models.shared.suppliers import Suppliers +from codat_sync_for_expenses.models.sync_complete_webhook import SyncCompleteWebhook +from codat_sync_for_expenses.models.sync_complete_webhook_data import SyncCompleteWebhookData +from codat_sync_for_expenses.models.sync_failed_webhook import SyncFailedWebhook +from codat_sync_for_expenses.models.sync_failed_webhook_data import SyncFailedWebhookData +from codat_sync_for_expenses.models.sync_initiated import SyncInitiated +from codat_sync_for_expenses.models.shared.taxratemappinginfo import TaxRateMappingInfo +from codat_sync_for_expenses.models.shared.trackingcategorymappinginfo import TrackingCategoryMappingInfo +from codat_sync_for_expenses.models.shared.trackingref import TrackingRef +from codat_sync_for_expenses.models.shared.trackingrefadjustmenttransaction import TrackingRefAdjustmentTransaction +from codat_sync_for_expenses.models.transaction import Transaction +from codat_sync_for_expenses.models.shared.transactionstatus import TransactionStatus +from codat_sync_for_expenses.models.shared.transactions import Transactions +from codat_sync_for_expenses.models.shared.transfertransactionrequest import TransferTransactionRequest +from codat_sync_for_expenses.models.transfer_transaction_request_from import TransferTransactionRequestFrom +from codat_sync_for_expenses.models.transfer_transaction_request_to import TransferTransactionRequestTo +from codat_sync_for_expenses.models.shared.transfertransactionresponse import TransferTransactionResponse +from codat_sync_for_expenses.models.update_connection import UpdateConnection +from codat_sync_for_expenses.models.shared.updatecustomerresponse import UpdateCustomerResponse +from codat_sync_for_expenses.models.update_customer_response_all_of_data import UpdateCustomerResponseAllOfData +from codat_sync_for_expenses.models.shared.updateexpenserequest import UpdateExpenseRequest +from codat_sync_for_expenses.models.shared.updateexpenseresponse import UpdateExpenseResponse +from codat_sync_for_expenses.models.shared.updatereimbursableexpensetransactionrequest import UpdateReimbursableExpenseTransactionRequest +from codat_sync_for_expenses.models.shared.updatesupplierresponse import UpdateSupplierResponse +from codat_sync_for_expenses.models.update_supplier_response_all_of_data import UpdateSupplierResponseAllOfData +from codat_sync_for_expenses.models.valid_data_type_links import ValidDataTypeLinks +from codat_sync_for_expenses.models.shared.validation import Validation +from codat_sync_for_expenses.models.shared.validationitem import ValidationItem +from codat_sync_for_expenses.models.weblink import Weblink +from .sdk import CodatSyncExpenses from ._version import ( __title__, @@ -7,11 +184,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. +CodatSyncForExpenses = CodatSyncExpenses diff --git a/sync-for-expenses/src/codat_sync_for_expenses/_hooks/__init__.py b/sync-for-expenses/src/codat_sync_for_expenses/_hooks/__init__.py index 2ee66cdd5..9a9b25d03 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/_hooks/__init__.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/_hooks/__init__.py @@ -1,5 +1,28 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""Hooks public surface.""" -from .sdkhooks import * -from .types import * -from .registration 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-expenses/src/codat_sync_for_expenses/_hooks/sdkhooks.py b/sync-for-expenses/src/codat_sync_for_expenses/_hooks/sdkhooks.py index 7f6fec9c8..d130d2d60 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/_hooks/sdkhooks.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/_hooks/sdkhooks.py @@ -1,19 +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 .registration import init_hooks -from typing import List, Optional, Tuple -from codat_sync_for_expenses.httpclient import HttpClient class SDKHooks(Hooks): @@ -36,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): @@ -65,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-expenses/src/codat_sync_for_expenses/_hooks/types.py b/sync-for-expenses/src/codat_sync_for_expenses/_hooks/types.py index fbff2b21d..5abf97b02 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/_hooks/types.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/_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_expenses.httpclient import HttpClient -from codat_sync_for_expenses.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-expenses/src/codat_sync_for_expenses/_httpx_transport.py b/sync-for-expenses/src/codat_sync_for_expenses/_httpx_transport.py new file mode 100644 index 000000000..68ec2095f --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/_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-expenses/src/codat_sync_for_expenses/_version.py b/sync-for-expenses/src/codat_sync_for_expenses/_version.py index 80f919843..387036fe0 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/_version.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/_version.py @@ -1,14 +1,17 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""Version metadata for codat-sync-for-expenses. + +Generated by pipeline/postprocess_generated.py — do not edit by hand. +""" + +from __future__ import annotations import importlib.metadata __title__: str = "codat-sync-for-expenses" -__version__: str = "8.0.1" +__version__: str = "0.0.0" __openapi_doc_version__: str = "prealpha" -__gen_version__: str = "2.881.4" -__user_agent__: str = ( - "speakeasy-sdk/python 8.0.1 2.881.4 prealpha codat-sync-for-expenses" -) +__gen_version__: str = "codat-sdk-codegen-poc-0.1.0" +__user_agent__: str = "codat-sdk/python 0.0.0 codat-sdk-codegen-poc-0.1.0 prealpha codat-sync-for-expenses" try: if __package__ is not None: diff --git a/sync-for-expenses/src/codat_sync_for_expenses/accounts.py b/sync-for-expenses/src/codat_sync_for_expenses/accounts.py index 9a5c1d0be..3744a7239 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/accounts.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/accounts.py @@ -1,447 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.accounts — re-export of the accounts method group.""" -from .basesdk import BaseSDK -from codat_sync_for_expenses import utils -from codat_sync_for_expenses._hooks import HookContext -from codat_sync_for_expenses.models import errors, operations, shared -from codat_sync_for_expenses.types import BaseModel, OptionalNullable, UNSET -from codat_sync_for_expenses.utils.unmarshal_json_response import ( - unmarshal_json_response, -) -from typing import Any, Mapping, Optional, Union, cast - - -class Accounts(BaseSDK): - r"""Create accounts and view create account options.""" - - def create( - self, - *, - request: Union[ - operations.CreateAccountRequest, operations.CreateAccountRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.CreateAccountResponse: - r"""Create account - - The *Create account* endpoint creates a new [account](https://docs.codat.io/sync-for-expenses-api#/schemas/Account) for a given company's connection. - - [Accounts](https://docs.codat.io/sync-for-expenses-api#/schemas/Account) are the categories a business uses to record accounting transactions. - - **Integration-specific behavior** - - Required data may vary by integration. To see what data to post, first call [Get create account model](https://docs.codat.io/sync-for-expenses-api#/operations/get-create-chartOfAccounts-model). - - :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.CreateAccountRequest) - request = cast(operations.CreateAccountRequest, request) - - req = self._build_request( - method="POST", - path="/companies/{companyId}/connections/{connectionId}/push/accounts", - 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.account_prototype if request is not None else None, - False, - True, - "json", - Optional[shared.AccountPrototype], - ), - 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-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, "200", "application/json"): - return unmarshal_json_response(shared.CreateAccountResponse, 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.CreateAccountRequest, operations.CreateAccountRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.CreateAccountResponse: - r"""Create account - - The *Create account* endpoint creates a new [account](https://docs.codat.io/sync-for-expenses-api#/schemas/Account) for a given company's connection. - - [Accounts](https://docs.codat.io/sync-for-expenses-api#/schemas/Account) are the categories a business uses to record accounting transactions. - - **Integration-specific behavior** - - Required data may vary by integration. To see what data to post, first call [Get create account model](https://docs.codat.io/sync-for-expenses-api#/operations/get-create-chartOfAccounts-model). - - :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.CreateAccountRequest) - request = cast(operations.CreateAccountRequest, request) - - req = self._build_request_async( - method="POST", - path="/companies/{companyId}/connections/{connectionId}/push/accounts", - 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.account_prototype if request is not None else None, - False, - True, - "json", - Optional[shared.AccountPrototype], - ), - 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-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, "200", "application/json"): - return unmarshal_json_response(shared.CreateAccountResponse, 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 get_create_model( - self, - *, - request: Union[ - operations.GetCreateChartOfAccountsModelRequest, - operations.GetCreateChartOfAccountsModelRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.PushOption: - r"""Get create account model - - The *Get create account model* endpoint returns the expected data for the request payload when creating an [account](https://docs.codat.io/sync-for-expenses-api#/schemas/Account) for a given company and integration. - - [Accounts](https://docs.codat.io/sync-for-expenses-api#/schemas/Account) are the categories a business uses to record accounting transactions. - - **Integration-specific behavior** - - See the *response examples* for integration-specific indicative models. - - :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.GetCreateChartOfAccountsModelRequest - ) - request = cast(operations.GetCreateChartOfAccountsModelRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/connections/{connectionId}/options/chartOfAccounts", - 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-create-chartOfAccounts-model", - 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.PushOption, 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_create_model_async( - self, - *, - request: Union[ - operations.GetCreateChartOfAccountsModelRequest, - operations.GetCreateChartOfAccountsModelRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.PushOption: - r"""Get create account model - - The *Get create account model* endpoint returns the expected data for the request payload when creating an [account](https://docs.codat.io/sync-for-expenses-api#/schemas/Account) for a given company and integration. - - [Accounts](https://docs.codat.io/sync-for-expenses-api#/schemas/Account) are the categories a business uses to record accounting transactions. - - **Integration-specific behavior** - - See the *response examples* for integration-specific indicative models. - - :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.GetCreateChartOfAccountsModelRequest - ) - request = cast(operations.GetCreateChartOfAccountsModelRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/connections/{connectionId}/options/chartOfAccounts", - 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-create-chartOfAccounts-model", - 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.PushOption, 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_expenses.api.accounts import Accounts diff --git a/sync-for-expenses/src/codat_sync_for_expenses/adjustments.py b/sync-for-expenses/src/codat_sync_for_expenses/adjustments.py index d6ed505d4..48d30f54c 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/adjustments.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/adjustments.py @@ -1,249 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.adjustments — re-export of the adjustments method group.""" -from .basesdk import BaseSDK -from codat_sync_for_expenses import utils -from codat_sync_for_expenses._hooks import HookContext -from codat_sync_for_expenses.models import errors, operations, shared -from codat_sync_for_expenses.types import BaseModel, OptionalNullable, UNSET -from codat_sync_for_expenses.utils.unmarshal_json_response import ( - unmarshal_json_response, -) -from typing import Any, List, Mapping, Optional, Union, cast - - -class Adjustments(BaseSDK): - r"""Create transactions that represent your adjustments to your customers' spend.""" - - def create( - self, - *, - request: Union[ - operations.CreateAdjustmentTransactionRequest, - operations.CreateAdjustmentTransactionRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.AdjustmentTransactionResponse: - r"""Create adjustment transaction - - Use the *Create adjustment expense* endpoint to create an [adjustment](https://docs.codat.io/sync-for-expenses-api#/schemas/AdjustmentTransactionRequest) in the accounting software for a given company's connection. - - Adjustments represent write-offs and transaction alterations, such as foreign exchange adjustments, in the form of a journal entry. - - ### Supported Integrations - - | Integration | Supported | - |-----------------------|-----------| - | QuickBooks Desktop | 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.CreateAdjustmentTransactionRequest - ) - request = cast(operations.CreateAdjustmentTransactionRequest, request) - - req = self._build_request( - method="POST", - path="/companies/{companyId}/sync/expenses/adjustment-transactions", - 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[List[shared.AdjustmentTransactionRequest]], - ), - 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-adjustment-transaction", - 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.AdjustmentTransactionResponse, 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.CreateAdjustmentTransactionRequest, - operations.CreateAdjustmentTransactionRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.AdjustmentTransactionResponse: - r"""Create adjustment transaction - - Use the *Create adjustment expense* endpoint to create an [adjustment](https://docs.codat.io/sync-for-expenses-api#/schemas/AdjustmentTransactionRequest) in the accounting software for a given company's connection. - - Adjustments represent write-offs and transaction alterations, such as foreign exchange adjustments, in the form of a journal entry. - - ### Supported Integrations - - | Integration | Supported | - |-----------------------|-----------| - | QuickBooks Desktop | 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.CreateAdjustmentTransactionRequest - ) - request = cast(operations.CreateAdjustmentTransactionRequest, request) - - req = self._build_request_async( - method="POST", - path="/companies/{companyId}/sync/expenses/adjustment-transactions", - 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[List[shared.AdjustmentTransactionRequest]], - ), - 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-adjustment-transaction", - 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.AdjustmentTransactionResponse, 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_expenses.api.adjustments import Adjustments diff --git a/sync-for-expenses/src/codat_sync_for_expenses/api/__init__.py b/sync-for-expenses/src/codat_sync_for_expenses/api/__init__.py new file mode 100644 index 000000000..ea79fecc5 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/api/__init__.py @@ -0,0 +1,22 @@ +# flake8: noqa + +# import apis into api package +from codat_sync_for_expenses.api.accounts import Accounts +from codat_sync_for_expenses.api.adjustments import Adjustments +from codat_sync_for_expenses.api.attachments import Attachments +from codat_sync_for_expenses.api.bank_accounts import BankAccounts +from codat_sync_for_expenses.api.companies import Companies +from codat_sync_for_expenses.api.company_info import CompanyInfo +from codat_sync_for_expenses.api.configuration import Configuration +from codat_sync_for_expenses.api.connections import Connections +from codat_sync_for_expenses.api.customers import Customers +from codat_sync_for_expenses.api.expenses import Expenses +from codat_sync_for_expenses.api.manage_data import ManageData +from codat_sync_for_expenses.api.mapping_options import MappingOptions +from codat_sync_for_expenses.api.push_operations import PushOperations +from codat_sync_for_expenses.api.reimbursements import Reimbursements +from codat_sync_for_expenses.api.suppliers import Suppliers +from codat_sync_for_expenses.api.sync import Sync +from codat_sync_for_expenses.api.transaction_status import TransactionStatus +from codat_sync_for_expenses.api.transfers import Transfers + diff --git a/sync-for-expenses/src/codat_sync_for_expenses/api/accounts.py b/sync-for-expenses/src/codat_sync_for_expenses/api/accounts.py new file mode 100644 index 000000000..7bb815569 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/api/accounts.py @@ -0,0 +1,519 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.models.shared.companies import Companies +from codat_sync_for_expenses.models.shared.connections import Connections +from codat_sync_for_expenses.models.shared.contact import Contact +from codat_sync_for_expenses.models.shared.customers import Customers +from codat_sync_for_expenses.models.shared.suppliers import Suppliers +from codat_sync_for_expenses.models.transaction import Transaction +from codat_sync_for_expenses.models.shared.accountprototype import AccountPrototype +from codat_sync_for_expenses.models.shared.createaccountresponse import CreateAccountResponse +from codat_sync_for_expenses.models.shared.pushoption import PushOption + +from codat_sync_for_expenses.api_client import ApiClient, RequestSerialized +from codat_sync_for_expenses.api_response import ApiResponse +from codat_sync_for_expenses.exceptions import ApiException +from codat_sync_for_expenses.models.errors import ErrorMessage, SDKError +from codat_sync_for_expenses.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_sync_for_expenses.rest import RESTResponseType +from codat_sync_for_expenses.types import UNSET, OptionalNullable +from codat_sync_for_expenses.utils.retries import RetryConfig, execute_with_retries + + +class CreateAccountRequestTypedDict(TypedDict): + """TypedDict variant of CreateAccountRequest, 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.")] + timeout_in_minutes: NotRequired[Annotated[Optional[int], Field(description="Time limit for the push operation to complete before it is timed out.")]] + allow_sync_on_push_complete: NotRequired[Annotated[Optional[bool], Field(description="Allow a sync upon push completion.")]] + account_prototype: NotRequired[Optional[AccountPrototype]] + + +class CreateAccountRequest(BaseModel): + """Request envelope for create_account.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + timeout_in_minutes: Annotated[Optional[int], Field(description="Time limit for the push operation to complete before it is timed out.")] = None + allow_sync_on_push_complete: Annotated[Optional[bool], Field(description="Allow a sync upon push completion.")] = True + account_prototype: Optional[AccountPrototype] = 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 GetCreateChartOfAccountsModelRequestTypedDict(TypedDict): + """TypedDict variant of GetCreateChartOfAccountsModelRequest, 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 GetCreateChartOfAccountsModelRequest(BaseModel): + """Request envelope for get_create_chart_of_accounts_model.""" + 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 Accounts: + """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['CreateAccountRequest', 'CreateAccountRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> CreateAccountResponse: + """Create account""" # noqa: E501 + + if isinstance(request, dict): + request = CreateAccountRequest.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_account_serialize( + company_id=request.company_id, + connection_id=request.connection_id, + timeout_in_minutes=request.timeout_in_minutes, + allow_sync_on_push_complete=request.allow_sync_on_push_complete, + account_prototype=request.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]] = { + '200': "CreateAccountResponse", + '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-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['CreateAccountRequest', 'CreateAccountRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> CreateAccountResponse: + 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_account_serialize( + self, + company_id, + connection_id, + timeout_in_minutes, + allow_sync_on_push_complete, + 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 + if timeout_in_minutes is not None: + + _query_params.append(('timeoutInMinutes', timeout_in_minutes)) + + if allow_sync_on_push_complete is not None: + + _query_params.append(('allowSyncOnPushComplete', allow_sync_on_push_complete)) + + # process the header parameters + # process the form parameters + # process the body parameter + if account_prototype is not None: + _body_params = 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}/push/accounts', + 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_create_model( + self, + *, + request: Union['GetCreateChartOfAccountsModelRequest', 'GetCreateChartOfAccountsModelRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> PushOption: + """Get create account model""" # noqa: E501 + + if isinstance(request, dict): + request = GetCreateChartOfAccountsModelRequest.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_create_chart_of_accounts_model_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': "PushOption", + '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-create-chartOfAccounts-model', + ) + 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_create_model_async( + self, + *, + request: Union['GetCreateChartOfAccountsModelRequest', 'GetCreateChartOfAccountsModelRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> PushOption: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.get_create_model( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _get_create_chart_of_accounts_model_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}/options/chartOfAccounts', + 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-expenses/src/codat_sync_for_expenses/api/adjustments.py b/sync-for-expenses/src/codat_sync_for_expenses/api/adjustments.py new file mode 100644 index 000000000..b56060be2 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/api/adjustments.py @@ -0,0 +1,282 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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 List, Optional +from typing_extensions import Annotated +from codat_sync_for_expenses.models.shared.companies import Companies +from codat_sync_for_expenses.models.shared.connections import Connections +from codat_sync_for_expenses.models.shared.contact import Contact +from codat_sync_for_expenses.models.shared.customers import Customers +from codat_sync_for_expenses.models.shared.suppliers import Suppliers +from codat_sync_for_expenses.models.transaction import Transaction +from codat_sync_for_expenses.models.shared.adjustmenttransactionrequest import AdjustmentTransactionRequest +from codat_sync_for_expenses.models.shared.adjustmenttransactionresponse import AdjustmentTransactionResponse + +from codat_sync_for_expenses.api_client import ApiClient, RequestSerialized +from codat_sync_for_expenses.api_response import ApiResponse +from codat_sync_for_expenses.exceptions import ApiException +from codat_sync_for_expenses.models.errors import ErrorMessage, SDKError +from codat_sync_for_expenses.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_sync_for_expenses.rest import RESTResponseType +from codat_sync_for_expenses.types import UNSET, OptionalNullable +from codat_sync_for_expenses.utils.retries import RetryConfig, execute_with_retries + + +class CreateAdjustmentTransactionRequestTypedDict(TypedDict): + """TypedDict variant of CreateAdjustmentTransactionRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + request_body: NotRequired[Optional[List[AdjustmentTransactionRequest]]] + + +class CreateAdjustmentTransactionRequest(BaseModel): + """Request envelope for create_adjustment_transaction.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + request_body: Optional[List[AdjustmentTransactionRequest]] = 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 Adjustments: + """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['CreateAdjustmentTransactionRequest', 'CreateAdjustmentTransactionRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> AdjustmentTransactionResponse: + """Create adjustment transaction""" # noqa: E501 + + if isinstance(request, dict): + request = CreateAdjustmentTransactionRequest.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_adjustment_transaction_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': "AdjustmentTransactionResponse", + '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-adjustment-transaction', + ) + 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['CreateAdjustmentTransactionRequest', 'CreateAdjustmentTransactionRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> AdjustmentTransactionResponse: + 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_adjustment_transaction_serialize( + self, + company_id, + request_body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + 'requestBody': '', + } + + _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}/sync/expenses/adjustment-transactions', + 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-expenses/src/codat_sync_for_expenses/api/attachments.py b/sync-for-expenses/src/codat_sync_for_expenses/api/attachments.py new file mode 100644 index 000000000..61c386063 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/api/attachments.py @@ -0,0 +1,300 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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 Tuple, Union +from typing_extensions import Annotated +from codat_sync_for_expenses.models.shared.companies import Companies +from codat_sync_for_expenses.models.shared.attachmentupload import AttachmentUpload +from codat_sync_for_expenses.models.shared.connections import Connections +from codat_sync_for_expenses.models.shared.contact import Contact +from codat_sync_for_expenses.models.shared.customers import Customers +from codat_sync_for_expenses.models.shared.suppliers import Suppliers +from codat_sync_for_expenses.models.transaction import Transaction +from codat_sync_for_expenses.models.shared.attachment import Attachment + +from codat_sync_for_expenses.api_client import ApiClient, RequestSerialized +from codat_sync_for_expenses.api_response import ApiResponse +from codat_sync_for_expenses.exceptions import ApiException +from codat_sync_for_expenses.models.errors import ErrorMessage, SDKError +from codat_sync_for_expenses.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_sync_for_expenses.rest import RESTResponseType +from codat_sync_for_expenses.types import UNSET, OptionalNullable +from codat_sync_for_expenses.utils.retries import RetryConfig, execute_with_retries + + +class UploadExpenseAttachmentRequestTypedDict(TypedDict): + """TypedDict variant of UploadExpenseAttachmentRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + sync_id: Annotated[str, Field(description="Unique identifier for a sync.")] + transaction_id: Annotated[str, Field(description="The unique identifier for your SMB's transaction.")] + attachment_upload: NotRequired[Optional[AttachmentUpload]] + + +class UploadExpenseAttachmentRequest(BaseModel): + """Request envelope for upload_expense_attachment.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + sync_id: Annotated[str, Field(description="Unique identifier for a sync.")] + transaction_id: Annotated[str, Field(description="The unique identifier for your SMB's transaction.")] + 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 Attachments: + """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 upload( + self, + *, + request: Union['UploadExpenseAttachmentRequest', 'UploadExpenseAttachmentRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Attachment: + """Upload attachment""" # noqa: E501 + + if isinstance(request, dict): + request = UploadExpenseAttachmentRequest.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_expense_attachment_serialize( + company_id=request.company_id, + sync_id=request.sync_id, + transaction_id=request.transaction_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]] = { + '200': "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-expense-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_async( + self, + *, + request: Union['UploadExpenseAttachmentRequest', 'UploadExpenseAttachmentRequestTypedDict'], + 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( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _upload_expense_attachment_serialize( + self, + company_id, + sync_id, + transaction_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 sync_id is not None: + _path_params['syncId'] = sync_id + if transaction_id is not None: + _path_params['transactionId'] = transaction_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}/sync/expenses/syncs/{syncId}/transactions/{transactionId}/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-expenses/src/codat_sync_for_expenses/api/bank_accounts.py b/sync-for-expenses/src/codat_sync_for_expenses/api/bank_accounts.py new file mode 100644 index 000000000..9d63adeac --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/api/bank_accounts.py @@ -0,0 +1,519 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.models.shared.companies import Companies +from codat_sync_for_expenses.models.shared.connections import Connections +from codat_sync_for_expenses.models.shared.contact import Contact +from codat_sync_for_expenses.models.shared.customers import Customers +from codat_sync_for_expenses.models.shared.suppliers import Suppliers +from codat_sync_for_expenses.models.transaction import Transaction +from codat_sync_for_expenses.models.shared.bankaccount import BankAccount +from codat_sync_for_expenses.models.create_bank_account_response import CreateBankAccountResponse +from codat_sync_for_expenses.models.shared.pushoption import PushOption + +from codat_sync_for_expenses.api_client import ApiClient, RequestSerialized +from codat_sync_for_expenses.api_response import ApiResponse +from codat_sync_for_expenses.exceptions import ApiException +from codat_sync_for_expenses.models.errors import ErrorMessage, SDKError +from codat_sync_for_expenses.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_sync_for_expenses.rest import RESTResponseType +from codat_sync_for_expenses.types import UNSET, OptionalNullable +from codat_sync_for_expenses.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.")] + timeout_in_minutes: NotRequired[Annotated[Optional[int], Field(description="Time limit for the push operation to complete before it is timed out.")]] + allow_sync_on_push_complete: NotRequired[Annotated[Optional[bool], Field(description="Allow a sync upon push completion.")]] + bank_account: NotRequired[Optional[BankAccount]] + + +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.")] + timeout_in_minutes: Annotated[Optional[int], Field(description="Time limit for the push operation to complete before it is timed out.")] = None + allow_sync_on_push_complete: Annotated[Optional[bool], Field(description="Allow a sync upon push completion.")] = True + bank_account: Optional[BankAccount] = 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 GetCreateBankAccountsModelRequestTypedDict(TypedDict): + """TypedDict variant of GetCreateBankAccountsModelRequest, 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 GetCreateBankAccountsModelRequest(BaseModel): + """Request envelope for get_create_bank_accounts_model.""" + 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 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, + ) -> CreateBankAccountResponse: + """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, + timeout_in_minutes=request.timeout_in_minutes, + allow_sync_on_push_complete=request.allow_sync_on_push_complete, + bank_account=request.bank_account, + _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': "CreateBankAccountResponse", + '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, + ) -> CreateBankAccountResponse: + 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, + timeout_in_minutes, + allow_sync_on_push_complete, + bank_account, + _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 timeout_in_minutes is not None: + + _query_params.append(('timeoutInMinutes', timeout_in_minutes)) + + if allow_sync_on_push_complete is not None: + + _query_params.append(('allowSyncOnPushComplete', allow_sync_on_push_complete)) + + # process the header parameters + # process the form parameters + # process the body parameter + if bank_account is not None: + _body_params = bank_account + + + 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}/push/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 + ) + + + + + @validate_call(config={"arbitrary_types_allowed": True}) + def get_create_model( + self, + *, + request: Union['GetCreateBankAccountsModelRequest', 'GetCreateBankAccountsModelRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> PushOption: + """Get create bank account model""" # noqa: E501 + + if isinstance(request, dict): + request = GetCreateBankAccountsModelRequest.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_create_bank_accounts_model_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': "PushOption", + '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-create-bankAccounts-model', + ) + 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_create_model_async( + self, + *, + request: Union['GetCreateBankAccountsModelRequest', 'GetCreateBankAccountsModelRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> PushOption: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.get_create_model( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _get_create_bank_accounts_model_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}/options/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-expenses/src/codat_sync_for_expenses/api/companies.py b/sync-for-expenses/src/codat_sync_for_expenses/api/companies.py new file mode 100644 index 000000000..968c96f3c --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/api/companies.py @@ -0,0 +1,1391 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.models.shared.connections import Connections +from codat_sync_for_expenses.models.shared.contact import Contact +from codat_sync_for_expenses.models.shared.customers import Customers +from codat_sync_for_expenses.models.shared.suppliers import Suppliers +from codat_sync_for_expenses.models.transaction import Transaction +from codat_sync_for_expenses.models.shared.companies import Companies +from codat_sync_for_expenses.models.shared.company import Company +from codat_sync_for_expenses.models.shared.companyrequestbody import CompanyRequestBody, CompanyRequestBodyTypedDict +from codat_sync_for_expenses.models.shared.companyupdaterequest import CompanyUpdateRequest + +from codat_sync_for_expenses.api_client import ApiClient, RequestSerialized +from codat_sync_for_expenses.api_response import ApiResponse +from codat_sync_for_expenses.exceptions import ApiException +from codat_sync_for_expenses.models.errors import ErrorMessage, SDKError +from codat_sync_for_expenses.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_sync_for_expenses.rest import RESTResponseType +from codat_sync_for_expenses.types import UNSET, OptionalNullable +from codat_sync_for_expenses.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-expenses/src/codat_sync_for_expenses/api/company_info.py b/sync-for-expenses/src/codat_sync_for_expenses/api/company_info.py new file mode 100644 index 000000000..66cc06e76 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/api/company_info.py @@ -0,0 +1,261 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.models.shared.companies import Companies +from codat_sync_for_expenses.models.shared.connections import Connections +from codat_sync_for_expenses.models.shared.contact import Contact +from codat_sync_for_expenses.models.shared.customers import Customers +from codat_sync_for_expenses.models.shared.suppliers import Suppliers +from codat_sync_for_expenses.models.transaction import Transaction +from codat_sync_for_expenses.models.company_information import CompanyInformation + +from codat_sync_for_expenses.api_client import ApiClient, RequestSerialized +from codat_sync_for_expenses.api_response import ApiResponse +from codat_sync_for_expenses.exceptions import ApiException +from codat_sync_for_expenses.models.errors import ErrorMessage, SDKError +from codat_sync_for_expenses.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_sync_for_expenses.rest import RESTResponseType +from codat_sync_for_expenses.types import UNSET, OptionalNullable +from codat_sync_for_expenses.utils.retries import RetryConfig, execute_with_retries + + +class GetCompanyInfoRequestTypedDict(TypedDict): + """TypedDict variant of GetCompanyInfoRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + + +class GetCompanyInfoRequest(BaseModel): + """Request envelope for get_company_info.""" + 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 CompanyInfo: + """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['GetCompanyInfoRequest', 'GetCompanyInfoRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> CompanyInformation: + """Get company info""" # noqa: E501 + + if isinstance(request, dict): + request = GetCompanyInfoRequest.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_info_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': "CompanyInformation", + '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='get-company-info', + ) + 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['GetCompanyInfoRequest', 'GetCompanyInfoRequestTypedDict'], + 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_info_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}/data/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-expenses/src/codat_sync_for_expenses/api/configuration.py b/sync-for-expenses/src/codat_sync_for_expenses/api/configuration.py new file mode 100644 index 000000000..b40bdc46f --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/api/configuration.py @@ -0,0 +1,489 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.models.shared.companies import Companies +from codat_sync_for_expenses.models.shared.connections import Connections +from codat_sync_for_expenses.models.shared.contact import Contact +from codat_sync_for_expenses.models.shared.customers import Customers +from codat_sync_for_expenses.models.shared.suppliers import Suppliers +from codat_sync_for_expenses.models.transaction import Transaction +from codat_sync_for_expenses.models.shared.companyconfiguration import CompanyConfiguration + +from codat_sync_for_expenses.api_client import ApiClient, RequestSerialized +from codat_sync_for_expenses.api_response import ApiResponse +from codat_sync_for_expenses.exceptions import ApiException +from codat_sync_for_expenses.models.errors import ErrorMessage, SDKError +from codat_sync_for_expenses.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_sync_for_expenses.rest import RESTResponseType +from codat_sync_for_expenses.types import UNSET, OptionalNullable +from codat_sync_for_expenses.utils.retries import RetryConfig, execute_with_retries + + +class GetCompanyConfigurationRequestTypedDict(TypedDict): + """TypedDict variant of GetCompanyConfigurationRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + + +class GetCompanyConfigurationRequest(BaseModel): + """Request envelope for get_company_configuration.""" + 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 SetCompanyConfigurationRequestTypedDict(TypedDict): + """TypedDict variant of SetCompanyConfigurationRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + company_configuration: NotRequired[Optional[CompanyConfiguration]] + + +class SetCompanyConfigurationRequest(BaseModel): + """Request envelope for set_company_configuration.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + company_configuration: Optional[CompanyConfiguration] = 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 Configuration: + """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['GetCompanyConfigurationRequest', 'GetCompanyConfigurationRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> CompanyConfiguration: + """Get company configuration""" # noqa: E501 + + if isinstance(request, dict): + request = GetCompanyConfigurationRequest.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_configuration_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': "CompanyConfiguration", + '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-configuration', + ) + 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['GetCompanyConfigurationRequest', 'GetCompanyConfigurationRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> CompanyConfiguration: + 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_configuration_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}/sync/expenses/config', + 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 set( + self, + *, + request: Union['SetCompanyConfigurationRequest', 'SetCompanyConfigurationRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> CompanyConfiguration: + """Set company configuration""" # noqa: E501 + + if isinstance(request, dict): + request = SetCompanyConfigurationRequest.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._set_company_configuration_serialize( + company_id=request.company_id, + company_configuration=request.company_configuration, + _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': "CompanyConfiguration", + '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='set-company-configuration', + ) + 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 set_async( + self, + *, + request: Union['SetCompanyConfigurationRequest', 'SetCompanyConfigurationRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> CompanyConfiguration: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.set( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _set_company_configuration_serialize( + self, + company_id, + company_configuration, + _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_configuration is not None: + _body_params = company_configuration + + + 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}/sync/expenses/config', + 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-expenses/src/codat_sync_for_expenses/api/connections.py b/sync-for-expenses/src/codat_sync_for_expenses/api/connections.py new file mode 100644 index 000000000..c5257d537 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/api/connections.py @@ -0,0 +1,1396 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.models.shared.companies import Companies +from codat_sync_for_expenses.models.shared.contact import Contact +from codat_sync_for_expenses.models.shared.customers import Customers +from codat_sync_for_expenses.models.shared.suppliers import Suppliers +from codat_sync_for_expenses.models.transaction import Transaction +from codat_sync_for_expenses.models.shared.connection import Connection +from codat_sync_for_expenses.models.shared.connections import Connections +from codat_sync_for_expenses.models.create_connection_request import CreateConnectionRequest as CreateConnectionRequestBody +from codat_sync_for_expenses.models.update_connection import UpdateConnection + +from codat_sync_for_expenses.api_client import ApiClient, RequestSerialized +from codat_sync_for_expenses.api_response import ApiResponse +from codat_sync_for_expenses.exceptions import ApiException +from codat_sync_for_expenses.models.errors import ErrorMessage, SDKError +from codat_sync_for_expenses.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_sync_for_expenses.rest import RESTResponseType +from codat_sync_for_expenses.types import UNSET, OptionalNullable +from codat_sync_for_expenses.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 CreatePartnerExpenseConnectionRequestTypedDict(TypedDict): + """TypedDict variant of CreatePartnerExpenseConnectionRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + + +class CreatePartnerExpenseConnectionRequest(BaseModel): + """Request envelope for create_partner_expense_connection.""" + 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 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 create_partner_expense_connection( + self, + *, + request: Union['CreatePartnerExpenseConnectionRequest', 'CreatePartnerExpenseConnectionRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Connection: + """Create partner expense connection""" # noqa: E501 + + if isinstance(request, dict): + request = CreatePartnerExpenseConnectionRequest.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_partner_expense_connection_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': "Connection", + '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-partner-expense-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_partner_expense_connection_async( + self, + *, + request: Union['CreatePartnerExpenseConnectionRequest', 'CreatePartnerExpenseConnectionRequestTypedDict'], + 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_partner_expense_connection( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _create_partner_expense_connection_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='POST', + resource_path='/companies/{companyId}/sync/expenses/connections/partnerExpense', + 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-expenses/src/codat_sync_for_expenses/api/customers.py b/sync-for-expenses/src/codat_sync_for_expenses/api/customers.py new file mode 100644 index 000000000..1a31aa3e6 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/api/customers.py @@ -0,0 +1,1027 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.models.shared.companies import Companies +from codat_sync_for_expenses.models.shared.connections import Connections +from codat_sync_for_expenses.models.shared.contact import Contact +from codat_sync_for_expenses.models.shared.suppliers import Suppliers +from codat_sync_for_expenses.models.transaction import Transaction +from codat_sync_for_expenses.models.shared.createcustomerresponse import CreateCustomerResponse +from codat_sync_for_expenses.models.shared.customer import Customer +from codat_sync_for_expenses.models.shared.customers import Customers +from codat_sync_for_expenses.models.shared.updatecustomerresponse import UpdateCustomerResponse + +from codat_sync_for_expenses.api_client import ApiClient, RequestSerialized +from codat_sync_for_expenses.api_response import ApiResponse +from codat_sync_for_expenses.exceptions import ApiException +from codat_sync_for_expenses.models.errors import ErrorMessage, SDKError +from codat_sync_for_expenses.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_sync_for_expenses.rest import RESTResponseType +from codat_sync_for_expenses.types import UNSET, OptionalNullable +from codat_sync_for_expenses.utils.retries import RetryConfig, execute_with_retries + + +class CreateCustomerRequestTypedDict(TypedDict): + """TypedDict variant of CreateCustomerRequest, 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.")] + timeout_in_minutes: NotRequired[Annotated[Optional[int], Field(description="Time limit for the push operation to complete before it is timed out.")]] + allow_sync_on_push_complete: NotRequired[Annotated[Optional[bool], Field(description="Allow a sync upon push completion.")]] + customer: NotRequired[Optional[Customer]] + + +class CreateCustomerRequest(BaseModel): + """Request envelope for create_customer.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + timeout_in_minutes: Annotated[Optional[int], Field(description="Time limit for the push operation to complete before it is timed out.")] = None + allow_sync_on_push_complete: Annotated[Optional[bool], Field(description="Allow a sync upon push completion.")] = True + customer: Optional[Customer] = 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 GetCustomerRequestTypedDict(TypedDict): + """TypedDict variant of GetCustomerRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + customer_id: Annotated[str, Field(description="Unique identifier for a customer.")] + + +class GetCustomerRequest(BaseModel): + """Request envelope for get_customer.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + customer_id: Annotated[str, Field(description="Unique identifier for a customer.")] + + @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 ListCustomersRequestTypedDict(TypedDict): + """TypedDict variant of ListCustomersRequest, 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 ListCustomersRequest(BaseModel): + """Request envelope for list_customers.""" + 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 UpdateCustomerRequestTypedDict(TypedDict): + """TypedDict variant of UpdateCustomerRequest, 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.")] + customer_id: Annotated[str, Field(description="Unique identifier for a customer.")] + timeout_in_minutes: NotRequired[Annotated[Optional[int], Field(description="Time limit for the push operation to complete before it is timed out.")]] + allow_sync_on_push_complete: NotRequired[Annotated[Optional[bool], Field(description="Allow a sync upon push completion.")]] + force_update: NotRequired[Annotated[Optional[bool], Field(description="When updating data in the destination platform Codat checks the `sourceModifiedDate` against the `lastupdated` date from the accounting software, if they're different Codat will return an error suggesting you should initiate another pull of the data. If this is set to `true` then the update will override this check.")]] + customer: NotRequired[Optional[Customer]] + + +class UpdateCustomerRequest(BaseModel): + """Request envelope for update_customer.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + connection_id: Annotated[str, Field(description="Unique identifier for a connection.")] + customer_id: Annotated[str, Field(description="Unique identifier for a customer.")] + timeout_in_minutes: Annotated[Optional[int], Field(description="Time limit for the push operation to complete before it is timed out.")] = None + allow_sync_on_push_complete: Annotated[Optional[bool], Field(description="Allow a sync upon push completion.")] = True + force_update: Annotated[Optional[bool], Field(description="When updating data in the destination platform Codat checks the `sourceModifiedDate` against the `lastupdated` date from the accounting software, if they're different Codat will return an error suggesting you should initiate another pull of the data. If this is set to `true` then the update will override this check.")] = False + customer: Optional[Customer] = 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 Customers: + """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['CreateCustomerRequest', 'CreateCustomerRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> CreateCustomerResponse: + """Create customer""" # noqa: E501 + + if isinstance(request, dict): + request = CreateCustomerRequest.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_customer_serialize( + company_id=request.company_id, + connection_id=request.connection_id, + timeout_in_minutes=request.timeout_in_minutes, + allow_sync_on_push_complete=request.allow_sync_on_push_complete, + customer=request.customer, + _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': "CreateCustomerResponse", + '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-customer', + ) + 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['CreateCustomerRequest', 'CreateCustomerRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> CreateCustomerResponse: + 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_customer_serialize( + self, + company_id, + connection_id, + timeout_in_minutes, + allow_sync_on_push_complete, + customer, + _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 timeout_in_minutes is not None: + + _query_params.append(('timeoutInMinutes', timeout_in_minutes)) + + if allow_sync_on_push_complete is not None: + + _query_params.append(('allowSyncOnPushComplete', allow_sync_on_push_complete)) + + # process the header parameters + # process the form parameters + # process the body parameter + if customer is not None: + _body_params = customer + + + 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}/push/customers', + 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['GetCustomerRequest', 'GetCustomerRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Customer: + """Get customer""" # noqa: E501 + + if isinstance(request, dict): + request = GetCustomerRequest.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_customer_serialize( + company_id=request.company_id, + customer_id=request.customer_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': "Customer", + '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='get-customer', + ) + 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['GetCustomerRequest', 'GetCustomerRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Customer: + 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_customer_serialize( + self, + company_id, + customer_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 customer_id is not None: + _path_params['customerId'] = customer_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}/data/customers/{customerId}', + 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['ListCustomersRequest', 'ListCustomersRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Customers: + """List customers""" # noqa: E501 + + if isinstance(request, dict): + request = ListCustomersRequest.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_customers_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': "Customers", + '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-customers', + ) + 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['ListCustomersRequest', 'ListCustomersRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Customers: + 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_customers_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}/data/customers', + 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['UpdateCustomerRequest', 'UpdateCustomerRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> UpdateCustomerResponse: + """Update customer""" # noqa: E501 + + if isinstance(request, dict): + request = UpdateCustomerRequest.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_customer_serialize( + company_id=request.company_id, + connection_id=request.connection_id, + customer_id=request.customer_id, + timeout_in_minutes=request.timeout_in_minutes, + allow_sync_on_push_complete=request.allow_sync_on_push_complete, + force_update=request.force_update, + customer=request.customer, + _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': "UpdateCustomerResponse", + '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-customer', + ) + 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['UpdateCustomerRequest', 'UpdateCustomerRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> UpdateCustomerResponse: + 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_customer_serialize( + self, + company_id, + connection_id, + customer_id, + timeout_in_minutes, + allow_sync_on_push_complete, + force_update, + customer, + _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 customer_id is not None: + _path_params['customerId'] = customer_id + # process the query parameters + if timeout_in_minutes is not None: + + _query_params.append(('timeoutInMinutes', timeout_in_minutes)) + + if allow_sync_on_push_complete is not None: + + _query_params.append(('allowSyncOnPushComplete', allow_sync_on_push_complete)) + + if force_update is not None: + + _query_params.append(('forceUpdate', force_update)) + + # process the header parameters + # process the form parameters + # process the body parameter + if customer is not None: + _body_params = customer + + + 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}/push/customers/{customerId}', + 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-expenses/src/codat_sync_for_expenses/api/expenses.py b/sync-for-expenses/src/codat_sync_for_expenses/api/expenses.py new file mode 100644 index 000000000..38bea1c1f --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/api/expenses.py @@ -0,0 +1,519 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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 List, Optional +from typing_extensions import Annotated +from codat_sync_for_expenses.models.shared.companies import Companies +from codat_sync_for_expenses.models.shared.connections import Connections +from codat_sync_for_expenses.models.shared.contact import Contact +from codat_sync_for_expenses.models.shared.customers import Customers +from codat_sync_for_expenses.models.shared.suppliers import Suppliers +from codat_sync_for_expenses.models.transaction import Transaction +from codat_sync_for_expenses.models.shared.createexpenseresponse import CreateExpenseResponse +from codat_sync_for_expenses.models.shared.expensetransaction import ExpenseTransaction +from codat_sync_for_expenses.models.shared.updateexpenserequest import UpdateExpenseRequest +from codat_sync_for_expenses.models.shared.updateexpenseresponse import UpdateExpenseResponse + +from codat_sync_for_expenses.api_client import ApiClient, RequestSerialized +from codat_sync_for_expenses.api_response import ApiResponse +from codat_sync_for_expenses.exceptions import ApiException +from codat_sync_for_expenses.models.errors import ErrorMessage, SDKError +from codat_sync_for_expenses.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_sync_for_expenses.rest import RESTResponseType +from codat_sync_for_expenses.types import UNSET, OptionalNullable +from codat_sync_for_expenses.utils.retries import RetryConfig, execute_with_retries + + +class CreateExpenseTransactionRequestTypedDict(TypedDict): + """TypedDict variant of CreateExpenseTransactionRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + request_body: NotRequired[Optional[List[ExpenseTransaction]]] + + +class CreateExpenseTransactionRequest(BaseModel): + """Request envelope for create_expense_transaction.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + request_body: Optional[List[ExpenseTransaction]] = 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 UpdateExpenseTransactionRequestTypedDict(TypedDict): + """TypedDict variant of UpdateExpenseTransactionRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + transaction_id: Annotated[str, Field(description="The unique identifier for your SMB's transaction.")] + update_expense_request: NotRequired[Optional[UpdateExpenseRequest]] + + +class UpdateExpenseTransactionRequest(BaseModel): + """Request envelope for update_expense_transaction.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + transaction_id: Annotated[str, Field(description="The unique identifier for your SMB's transaction.")] + update_expense_request: Optional[UpdateExpenseRequest] = 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 Expenses: + """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['CreateExpenseTransactionRequest', 'CreateExpenseTransactionRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> CreateExpenseResponse: + """Create expense transaction""" # noqa: E501 + + if isinstance(request, dict): + request = CreateExpenseTransactionRequest.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_expense_transaction_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': "CreateExpenseResponse", + '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-expense-transaction', + ) + 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['CreateExpenseTransactionRequest', 'CreateExpenseTransactionRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> CreateExpenseResponse: + 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_expense_transaction_serialize( + self, + company_id, + request_body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + 'requestBody': '', + } + + _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}/sync/expenses/expense-transactions', + 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['UpdateExpenseTransactionRequest', 'UpdateExpenseTransactionRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> UpdateExpenseResponse: + """Update expense transactions""" # noqa: E501 + + if isinstance(request, dict): + request = UpdateExpenseTransactionRequest.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_expense_transaction_serialize( + company_id=request.company_id, + transaction_id=request.transaction_id, + update_expense_request=request.update_expense_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]] = { + '202': "UpdateExpenseResponse", + '400': "ErrorMessage", + '401': "ErrorMessage", + '402': "ErrorMessage", + '403': "ErrorMessage", + '404': "ErrorMessage", + '422': "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-expense-transaction', + ) + 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['UpdateExpenseTransactionRequest', 'UpdateExpenseTransactionRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> UpdateExpenseResponse: + 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_expense_transaction_serialize( + self, + company_id, + transaction_id, + update_expense_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 + if transaction_id is not None: + _path_params['transactionId'] = transaction_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if update_expense_request is not None: + _body_params = update_expense_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='PUT', + resource_path='/companies/{companyId}/sync/expenses/expense-transactions/{transactionId}', + 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-expenses/src/codat_sync_for_expenses/api/manage_data.py b/sync-for-expenses/src/codat_sync_for_expenses/api/manage_data.py new file mode 100644 index 000000000..72ca1599f --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/api/manage_data.py @@ -0,0 +1,1156 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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, field_validator +from typing import Optional +from typing_extensions import Annotated +from codat_sync_for_expenses.models.shared.companies import Companies +from codat_sync_for_expenses.models.shared.connections import Connections +from codat_sync_for_expenses.models.shared.contact import Contact +from codat_sync_for_expenses.models.shared.customers import Customers +from codat_sync_for_expenses.models.shared.suppliers import Suppliers +from codat_sync_for_expenses.models.transaction import Transaction +from codat_sync_for_expenses.models.data_statuses import DataStatuses, GetDataStatusDataStatuses +from codat_sync_for_expenses.models.shared.datatype import DataType +from codat_sync_for_expenses.models.shared.pulloperation import PullOperation +from codat_sync_for_expenses.models.shared.pulloperations import PullOperations + +from codat_sync_for_expenses.api_client import ApiClient, RequestSerialized +from codat_sync_for_expenses.api_response import ApiResponse +from codat_sync_for_expenses.exceptions import ApiException +from codat_sync_for_expenses.models.errors import ErrorMessage, SDKError +from codat_sync_for_expenses.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_sync_for_expenses.rest import RESTResponseType +from codat_sync_for_expenses.types import UNSET, OptionalNullable +from codat_sync_for_expenses.utils.retries import RetryConfig, execute_with_retries + + +from codat_sync_for_expenses.models._compat.schema_datatype import SchemaDataType +class GetDataStatusRequestTypedDict(TypedDict): + """TypedDict variant of GetDataStatusRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + + +class GetDataStatusRequest(BaseModel): + """Request envelope for get_data_status.""" + 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 GetPullOperationRequestTypedDict(TypedDict): + """TypedDict variant of GetPullOperationRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + dataset_id: Annotated[str, Field(description="Unique identifier for the dataset that completed its sync.")] + + +class GetPullOperationRequest(BaseModel): + """Request envelope for get_pull_operation.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + dataset_id: Annotated[str, Field(description="Unique identifier for the dataset that completed its sync.")] + + @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 ListPullOperationsRequestTypedDict(TypedDict): + """TypedDict variant of ListPullOperationsRequest, 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 ListPullOperationsRequest(BaseModel): + """Request envelope for list_pull_operations.""" + 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 RefreshAllDataTypesRequestTypedDict(TypedDict): + """TypedDict variant of RefreshAllDataTypesRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + + +class RefreshAllDataTypesRequest(BaseModel): + """Request envelope for refresh_all_data_types.""" + 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 RefreshDataTypeRequestTypedDict(TypedDict): + """TypedDict variant of RefreshDataTypeRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + data_type: Annotated[SchemaDataType, Field(description="The key of a Codat data type")] + connection_id: NotRequired[Annotated[Optional[str], Field(description="Optionally, provide a data connection id to only queue pull operations on that connection.")]] + + +class RefreshDataTypeRequest(BaseModel): + """Request envelope for refresh_data_type.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + data_type: Annotated[SchemaDataType, Field(description="The key of a Codat data type")] + connection_id: Annotated[Optional[str], Field(description="Optionally, provide a data connection id to only queue pull operations on that connection.")] = 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 ManageData: + """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['GetDataStatusRequest', 'GetDataStatusRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> GetDataStatusDataStatuses: + """Get data status""" # noqa: E501 + + if isinstance(request, dict): + request = GetDataStatusRequest.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_data_status_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': "DataStatuses", + '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-data-status', + ) + 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['GetDataStatusRequest', 'GetDataStatusRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> GetDataStatusDataStatuses: + 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_data_status_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}/dataStatus', + 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_pull_operation( + self, + *, + request: Union['GetPullOperationRequest', 'GetPullOperationRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> PullOperation: + """Get pull operation""" # noqa: E501 + + if isinstance(request, dict): + request = GetPullOperationRequest.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_pull_operation_serialize( + company_id=request.company_id, + dataset_id=request.dataset_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': "PullOperation", + '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-pull-operation', + ) + 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_pull_operation_async( + self, + *, + request: Union['GetPullOperationRequest', 'GetPullOperationRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> PullOperation: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.get_pull_operation( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _get_pull_operation_serialize( + self, + company_id, + dataset_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 dataset_id is not None: + _path_params['datasetId'] = dataset_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}/data/history/{datasetId}', + 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_pull_operations( + self, + *, + request: Union['ListPullOperationsRequest', 'ListPullOperationsRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> PullOperations: + """List pull operations""" # noqa: E501 + + if isinstance(request, dict): + request = ListPullOperationsRequest.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_pull_operations_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': "PullOperations", + '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-pull-operations', + ) + 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_pull_operations_async( + self, + *, + request: Union['ListPullOperationsRequest', 'ListPullOperationsRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> PullOperations: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.list_pull_operations( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _list_pull_operations_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}/data/history', + 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 refresh_all_data_types( + self, + *, + request: Union['RefreshAllDataTypesRequest', 'RefreshAllDataTypesRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> None: + """Refresh all data""" # noqa: E501 + + if isinstance(request, dict): + request = RefreshAllDataTypesRequest.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._refresh_all_data_types_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, + '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='refresh-all-data-types', + ) + 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 refresh_all_data_types_async( + self, + *, + request: Union['RefreshAllDataTypesRequest', 'RefreshAllDataTypesRequestTypedDict'], + 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.refresh_all_data_types( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _refresh_all_data_types_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='POST', + resource_path='/companies/{companyId}/data/all', + 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 refresh_data_type( + self, + *, + request: Union['RefreshDataTypeRequest', 'RefreshDataTypeRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> PullOperation: + """Refresh data type""" # noqa: E501 + + if isinstance(request, dict): + request = RefreshDataTypeRequest.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._refresh_data_type_serialize( + company_id=request.company_id, + data_type=request.data_type, + 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': "PullOperation", + '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='refresh-data-type', + ) + 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 refresh_data_type_async( + self, + *, + request: Union['RefreshDataTypeRequest', 'RefreshDataTypeRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> PullOperation: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.refresh_data_type( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _refresh_data_type_serialize( + self, + company_id, + data_type, + 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 data_type is not None: + _path_params['dataType'] = data_type + # process the query parameters + if connection_id is not None: + + _query_params.append(('connectionId', connection_id)) + + # 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='POST', + resource_path='/companies/{companyId}/data/queue/{dataType}', + 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-expenses/src/codat_sync_for_expenses/api/mapping_options.py b/sync-for-expenses/src/codat_sync_for_expenses/api/mapping_options.py new file mode 100644 index 000000000..cef61f676 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/api/mapping_options.py @@ -0,0 +1,260 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.models.shared.companies import Companies +from codat_sync_for_expenses.models.shared.connections import Connections +from codat_sync_for_expenses.models.shared.contact import Contact +from codat_sync_for_expenses.models.shared.customers import Customers +from codat_sync_for_expenses.models.shared.suppliers import Suppliers +from codat_sync_for_expenses.models.transaction import Transaction +from codat_sync_for_expenses.models.shared.mappingoptions import MappingOptions + +from codat_sync_for_expenses.api_client import ApiClient, RequestSerialized +from codat_sync_for_expenses.api_response import ApiResponse +from codat_sync_for_expenses.exceptions import ApiException +from codat_sync_for_expenses.models.errors import ErrorMessage, SDKError +from codat_sync_for_expenses.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_sync_for_expenses.rest import RESTResponseType +from codat_sync_for_expenses.types import UNSET, OptionalNullable +from codat_sync_for_expenses.utils.retries import RetryConfig, execute_with_retries + + +class GetMappingOptionsRequestTypedDict(TypedDict): + """TypedDict variant of GetMappingOptionsRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + + +class GetMappingOptionsRequest(BaseModel): + """Request envelope for get_mapping_options.""" + 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 MappingOptions: + """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_mapping_options( + self, + *, + request: Union['GetMappingOptionsRequest', 'GetMappingOptionsRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> MappingOptions: + """Mapping options""" # noqa: E501 + + if isinstance(request, dict): + request = GetMappingOptionsRequest.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_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': "MappingOptions", + '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', + ) + 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_mapping_options_async( + self, + *, + request: Union['GetMappingOptionsRequest', 'GetMappingOptionsRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> MappingOptions: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.get_mapping_options( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _get_mapping_options_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}/sync/expenses/mappingOptions', + 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-expenses/src/codat_sync_for_expenses/api/push_operations.py b/sync-for-expenses/src/codat_sync_for_expenses/api/push_operations.py new file mode 100644 index 000000000..3bffc03d8 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/api/push_operations.py @@ -0,0 +1,510 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.models.shared.companies import Companies +from codat_sync_for_expenses.models.shared.connections import Connections +from codat_sync_for_expenses.models.shared.contact import Contact +from codat_sync_for_expenses.models.shared.customers import Customers +from codat_sync_for_expenses.models.shared.suppliers import Suppliers +from codat_sync_for_expenses.models.transaction import Transaction +from codat_sync_for_expenses.models.shared.pushoperation import PushOperation +from codat_sync_for_expenses.models.shared.pushoperations import PushOperations + +from codat_sync_for_expenses.api_client import ApiClient, RequestSerialized +from codat_sync_for_expenses.api_response import ApiResponse +from codat_sync_for_expenses.exceptions import ApiException +from codat_sync_for_expenses.models.errors import ErrorMessage, SDKError +from codat_sync_for_expenses.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_sync_for_expenses.rest import RESTResponseType +from codat_sync_for_expenses.types import UNSET, OptionalNullable +from codat_sync_for_expenses.utils.retries import RetryConfig, execute_with_retries + + +class GetPushOperationRequestTypedDict(TypedDict): + """TypedDict variant of GetPushOperationRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + push_operation_key: Annotated[str, Field(description="Push operation key.")] + + +class GetPushOperationRequest(BaseModel): + """Request envelope for get_push_operation.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + push_operation_key: Annotated[str, Field(description="Push operation key.")] + + @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 ListPushOperationsRequestTypedDict(TypedDict): + """TypedDict variant of ListPushOperationsRequest, 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 ListPushOperationsRequest(BaseModel): + """Request envelope for list_push_operations.""" + 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 PushOperations: + """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['GetPushOperationRequest', 'GetPushOperationRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> PushOperation: + """Get push operation""" # noqa: E501 + + if isinstance(request, dict): + request = GetPushOperationRequest.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_push_operation_serialize( + company_id=request.company_id, + push_operation_key=request.push_operation_key, + _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': "PushOperation", + '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-push-operation', + ) + 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['GetPushOperationRequest', 'GetPushOperationRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> PushOperation: + 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_push_operation_serialize( + self, + company_id, + push_operation_key, + _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 push_operation_key is not None: + _path_params['pushOperationKey'] = push_operation_key + # 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}/push/{pushOperationKey}', + 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['ListPushOperationsRequest', 'ListPushOperationsRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> PushOperations: + """List push operations""" # noqa: E501 + + if isinstance(request, dict): + request = ListPushOperationsRequest.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_push_operations_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': "PushOperations", + '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-push-operations', + ) + 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['ListPushOperationsRequest', 'ListPushOperationsRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> PushOperations: + 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_push_operations_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}/push', + 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-expenses/src/codat_sync_for_expenses/api/reimbursements.py b/sync-for-expenses/src/codat_sync_for_expenses/api/reimbursements.py new file mode 100644 index 000000000..21d95b450 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/api/reimbursements.py @@ -0,0 +1,517 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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 List, Optional +from typing_extensions import Annotated +from codat_sync_for_expenses.models.shared.companies import Companies +from codat_sync_for_expenses.models.shared.connections import Connections +from codat_sync_for_expenses.models.shared.contact import Contact +from codat_sync_for_expenses.models.shared.customers import Customers +from codat_sync_for_expenses.models.shared.suppliers import Suppliers +from codat_sync_for_expenses.models.transaction import Transaction +from codat_sync_for_expenses.models.shared.createreimbursableexpenseresponse import CreateReimbursableExpenseResponse +from codat_sync_for_expenses.models.shared.reimbursableexpensetransaction import ReimbursableExpenseTransaction +from codat_sync_for_expenses.models.shared.updatereimbursableexpensetransactionrequest import UpdateReimbursableExpenseTransactionRequest as UpdateReimbursableExpenseTransactionRequestBody + +from codat_sync_for_expenses.api_client import ApiClient, RequestSerialized +from codat_sync_for_expenses.api_response import ApiResponse +from codat_sync_for_expenses.exceptions import ApiException +from codat_sync_for_expenses.models.errors import ErrorMessage, SDKError +from codat_sync_for_expenses.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_sync_for_expenses.rest import RESTResponseType +from codat_sync_for_expenses.types import UNSET, OptionalNullable +from codat_sync_for_expenses.utils.retries import RetryConfig, execute_with_retries + + +class CreateReimbursableExpenseTransactionRequestTypedDict(TypedDict): + """TypedDict variant of CreateReimbursableExpenseTransactionRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + request_body: NotRequired[Optional[List[ReimbursableExpenseTransaction]]] + + +class CreateReimbursableExpenseTransactionRequest(BaseModel): + """Request envelope for create_reimbursable_expense_transaction.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + request_body: Optional[List[ReimbursableExpenseTransaction]] = 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 UpdateReimbursableExpenseTransactionRequestTypedDict(TypedDict): + """TypedDict variant of UpdateReimbursableExpenseTransactionRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + transaction_id: Annotated[str, Field(description="The unique identifier for your SMB's transaction.")] + update_reimbursable_expense_transaction_request: NotRequired[Optional[UpdateReimbursableExpenseTransactionRequestBody]] + + +class UpdateReimbursableExpenseTransactionRequest(BaseModel): + """Request envelope for update_reimbursable_expense_transaction.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + transaction_id: Annotated[str, Field(description="The unique identifier for your SMB's transaction.")] + update_reimbursable_expense_transaction_request: Optional[UpdateReimbursableExpenseTransactionRequestBody] = 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 Reimbursements: + """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['CreateReimbursableExpenseTransactionRequest', 'CreateReimbursableExpenseTransactionRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> CreateReimbursableExpenseResponse: + """Create reimbursable expense transaction""" # noqa: E501 + + if isinstance(request, dict): + request = CreateReimbursableExpenseTransactionRequest.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_reimbursable_expense_transaction_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': "CreateReimbursableExpenseResponse", + '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-reimbursable-expense-transaction', + ) + 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['CreateReimbursableExpenseTransactionRequest', 'CreateReimbursableExpenseTransactionRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> CreateReimbursableExpenseResponse: + 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_reimbursable_expense_transaction_serialize( + self, + company_id, + request_body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + 'requestBody': '', + } + + _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}/sync/expenses/reimbursable-expense-transactions', + 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['UpdateReimbursableExpenseTransactionRequest', 'UpdateReimbursableExpenseTransactionRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> CreateReimbursableExpenseResponse: + """Update reimbursable expense transaction""" # noqa: E501 + + if isinstance(request, dict): + request = UpdateReimbursableExpenseTransactionRequest.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_reimbursable_expense_transaction_serialize( + company_id=request.company_id, + transaction_id=request.transaction_id, + update_reimbursable_expense_transaction_request=request.update_reimbursable_expense_transaction_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': "CreateReimbursableExpenseResponse", + '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-reimbursable-expense-transaction', + ) + 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['UpdateReimbursableExpenseTransactionRequest', 'UpdateReimbursableExpenseTransactionRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> CreateReimbursableExpenseResponse: + 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_reimbursable_expense_transaction_serialize( + self, + company_id, + transaction_id, + update_reimbursable_expense_transaction_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 + if transaction_id is not None: + _path_params['transactionId'] = transaction_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if update_reimbursable_expense_transaction_request is not None: + _body_params = update_reimbursable_expense_transaction_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='PUT', + resource_path='/companies/{companyId}/sync/expenses/reimbursable-expense-transactions/{transactionId}', + 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-expenses/src/codat_sync_for_expenses/api/suppliers.py b/sync-for-expenses/src/codat_sync_for_expenses/api/suppliers.py new file mode 100644 index 000000000..3c876655d --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/api/suppliers.py @@ -0,0 +1,1027 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.models.shared.companies import Companies +from codat_sync_for_expenses.models.shared.connections import Connections +from codat_sync_for_expenses.models.shared.contact import Contact +from codat_sync_for_expenses.models.shared.customers import Customers +from codat_sync_for_expenses.models.transaction import Transaction +from codat_sync_for_expenses.models.shared.createsupplierresponse import CreateSupplierResponse +from codat_sync_for_expenses.models.shared.supplier import Supplier +from codat_sync_for_expenses.models.shared.suppliers import Suppliers +from codat_sync_for_expenses.models.shared.updatesupplierresponse import UpdateSupplierResponse + +from codat_sync_for_expenses.api_client import ApiClient, RequestSerialized +from codat_sync_for_expenses.api_response import ApiResponse +from codat_sync_for_expenses.exceptions import ApiException +from codat_sync_for_expenses.models.errors import ErrorMessage, SDKError +from codat_sync_for_expenses.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_sync_for_expenses.rest import RESTResponseType +from codat_sync_for_expenses.types import UNSET, OptionalNullable +from codat_sync_for_expenses.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.")] + timeout_in_minutes: NotRequired[Annotated[Optional[int], Field(description="Time limit for the push operation to complete before it is timed out.")]] + allow_sync_on_push_complete: NotRequired[Annotated[Optional[bool], Field(description="Allow a sync upon push completion.")]] + supplier: NotRequired[Optional[Supplier]] + + +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.")] + timeout_in_minutes: Annotated[Optional[int], Field(description="Time limit for the push operation to complete before it is timed out.")] = None + allow_sync_on_push_complete: Annotated[Optional[bool], Field(description="Allow a sync upon push completion.")] = True + supplier: Optional[Supplier] = 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 GetSupplierRequestTypedDict(TypedDict): + """TypedDict variant of GetSupplierRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + supplier_id: Annotated[str, Field(description="Unique identifier for a supplier.")] + + +class GetSupplierRequest(BaseModel): + """Request envelope for get_supplier.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + supplier_id: Annotated[str, Field(description="Unique identifier for a supplier.")] + + @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.")] + 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 ListSuppliersRequest(BaseModel): + """Request envelope for list_suppliers.""" + 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 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.")] + timeout_in_minutes: NotRequired[Annotated[Optional[int], Field(description="Time limit for the push operation to complete before it is timed out.")]] + allow_sync_on_push_complete: NotRequired[Annotated[Optional[bool], Field(description="Allow a sync upon push completion.")]] + force_update: NotRequired[Annotated[Optional[bool], Field(description="When updating data in the destination platform Codat checks the `sourceModifiedDate` against the `lastupdated` date from the accounting software, if they're different Codat will return an error suggesting you should initiate another pull of the data. If this is set to `true` then the update will override this check.")]] + supplier: NotRequired[Optional[Supplier]] + + +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.")] + timeout_in_minutes: Annotated[Optional[int], Field(description="Time limit for the push operation to complete before it is timed out.")] = None + allow_sync_on_push_complete: Annotated[Optional[bool], Field(description="Allow a sync upon push completion.")] = True + force_update: Annotated[Optional[bool], Field(description="When updating data in the destination platform Codat checks the `sourceModifiedDate` against the `lastupdated` date from the accounting software, if they're different Codat will return an error suggesting you should initiate another pull of the data. If this is set to `true` then the update will override this check.")] = False + supplier: Optional[Supplier] = 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, + ) -> CreateSupplierResponse: + """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, + timeout_in_minutes=request.timeout_in_minutes, + allow_sync_on_push_complete=request.allow_sync_on_push_complete, + supplier=request.supplier, + _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': "CreateSupplierResponse", + '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, + ) -> CreateSupplierResponse: + 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, + timeout_in_minutes, + allow_sync_on_push_complete, + supplier, + _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 timeout_in_minutes is not None: + + _query_params.append(('timeoutInMinutes', timeout_in_minutes)) + + if allow_sync_on_push_complete is not None: + + _query_params.append(('allowSyncOnPushComplete', allow_sync_on_push_complete)) + + # process the header parameters + # process the form parameters + # process the body parameter + if supplier is not None: + _body_params = supplier + + + 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}/push/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 get( + self, + *, + request: Union['GetSupplierRequest', 'GetSupplierRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Supplier: + """Get supplier""" # noqa: E501 + + if isinstance(request, dict): + request = GetSupplierRequest.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_supplier_serialize( + company_id=request.company_id, + supplier_id=request.supplier_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': "Supplier", + '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='get-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 get_async( + self, + *, + request: Union['GetSupplierRequest', 'GetSupplierRequestTypedDict'], + 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.get( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _get_supplier_serialize( + self, + company_id, + supplier_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 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 '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}/data/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 + ) + + + + + @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, + 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': "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, + 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}/data/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, + ) -> UpdateSupplierResponse: + """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, + timeout_in_minutes=request.timeout_in_minutes, + allow_sync_on_push_complete=request.allow_sync_on_push_complete, + force_update=request.force_update, + supplier=request.supplier, + _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': "UpdateSupplierResponse", + '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, + ) -> UpdateSupplierResponse: + 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, + timeout_in_minutes, + allow_sync_on_push_complete, + force_update, + supplier, + _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 + if timeout_in_minutes is not None: + + _query_params.append(('timeoutInMinutes', timeout_in_minutes)) + + if allow_sync_on_push_complete is not None: + + _query_params.append(('allowSyncOnPushComplete', allow_sync_on_push_complete)) + + if force_update is not None: + + _query_params.append(('forceUpdate', force_update)) + + # process the header parameters + # process the form parameters + # process the body parameter + if supplier is not None: + _body_params = supplier + + + 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}/push/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-expenses/src/codat_sync_for_expenses/api/sync.py b/sync-for-expenses/src/codat_sync_for_expenses/api/sync.py new file mode 100644 index 000000000..da228776c --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/api/sync.py @@ -0,0 +1,899 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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 List +from typing_extensions import Annotated +from codat_sync_for_expenses.models.shared.companies import Companies +from codat_sync_for_expenses.models.shared.connections import Connections +from codat_sync_for_expenses.models.shared.contact import Contact +from codat_sync_for_expenses.models.shared.customers import Customers +from codat_sync_for_expenses.models.shared.suppliers import Suppliers +from codat_sync_for_expenses.models.transaction import Transaction +from codat_sync_for_expenses.models.shared.companysyncstatus import CompanySyncStatus + +from codat_sync_for_expenses.api_client import ApiClient, RequestSerialized +from codat_sync_for_expenses.api_response import ApiResponse +from codat_sync_for_expenses.exceptions import ApiException +from codat_sync_for_expenses.models.errors import ErrorMessage, SDKError +from codat_sync_for_expenses.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_sync_for_expenses.rest import RESTResponseType +from codat_sync_for_expenses.types import UNSET, OptionalNullable +from codat_sync_for_expenses.utils.retries import RetryConfig, execute_with_retries + + +class GetLastSuccessfulSyncRequestTypedDict(TypedDict): + """TypedDict variant of GetLastSuccessfulSyncRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + + +class GetLastSuccessfulSyncRequest(BaseModel): + """Request envelope for get_last_successful_sync.""" + 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 GetLatestSyncRequestTypedDict(TypedDict): + """TypedDict variant of GetLatestSyncRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + + +class GetLatestSyncRequest(BaseModel): + """Request envelope for get_latest_sync.""" + 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 GetSyncByIDRequestTypedDict(TypedDict): + """TypedDict variant of GetSyncByIDRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + sync_id: Annotated[str, Field(description="Unique identifier for a sync.")] + + +class GetSyncByIDRequest(BaseModel): + """Request envelope for get_sync_by_id.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + sync_id: Annotated[str, Field(description="Unique identifier for a sync.")] + + @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 ListSyncsRequestTypedDict(TypedDict): + """TypedDict variant of ListSyncsRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + + +class ListSyncsRequest(BaseModel): + """Request envelope for list_syncs.""" + 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 Sync: + """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_last_successful_sync( + self, + *, + request: Union['GetLastSuccessfulSyncRequest', 'GetLastSuccessfulSyncRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> CompanySyncStatus: + """Last successful sync""" # noqa: E501 + + if isinstance(request, dict): + request = GetLastSuccessfulSyncRequest.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_last_successful_sync_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': "CompanySyncStatus", + '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-last-successful-sync', + ) + 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_last_successful_sync_async( + self, + *, + request: Union['GetLastSuccessfulSyncRequest', 'GetLastSuccessfulSyncRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> CompanySyncStatus: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.get_last_successful_sync( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _get_last_successful_sync_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}/sync/expenses/syncs/lastSuccessful/status', + 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_latest_sync( + self, + *, + request: Union['GetLatestSyncRequest', 'GetLatestSyncRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> CompanySyncStatus: + """Latest sync status""" # noqa: E501 + + if isinstance(request, dict): + request = GetLatestSyncRequest.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_latest_sync_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': "CompanySyncStatus", + '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-latest-sync', + ) + 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_latest_sync_async( + self, + *, + request: Union['GetLatestSyncRequest', 'GetLatestSyncRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> CompanySyncStatus: + return await asyncio.get_event_loop().run_in_executor( + None, + lambda: self.get_latest_sync( + request=request, + retries=retries, + server_url=server_url, + timeout_ms=timeout_ms, + http_headers=http_headers, + ), + ) + + + def _get_latest_sync_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}/sync/expenses/syncs/latest/status', + 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['GetSyncByIDRequest', 'GetSyncByIDRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> CompanySyncStatus: + """Get sync status""" # noqa: E501 + + if isinstance(request, dict): + request = GetSyncByIDRequest.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_sync_by_id_serialize( + company_id=request.company_id, + sync_id=request.sync_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': "CompanySyncStatus", + '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-sync-by-id', + ) + 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['GetSyncByIDRequest', 'GetSyncByIDRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> CompanySyncStatus: + 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_sync_by_id_serialize( + self, + company_id, + sync_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 sync_id is not None: + _path_params['syncId'] = sync_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}/sync/expenses/syncs/{syncId}/status', + 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['ListSyncsRequest', 'ListSyncsRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> List[CompanySyncStatus]: + """List sync statuses""" # noqa: E501 + + if isinstance(request, dict): + request = ListSyncsRequest.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_syncs_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': "List[CompanySyncStatus]", + '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-syncs', + ) + 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['ListSyncsRequest', 'ListSyncsRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> List[CompanySyncStatus]: + 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_syncs_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}/sync/expenses/syncs/list/status', + 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 + ) + + + + +# POC spelling of GetSyncByIDRequest, kept as an alias so existing imports keep working. +GetSyncByIdRequest = GetSyncByIDRequest +GetSyncByIdRequestTypedDict = GetSyncByIDRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/api/transaction_status.py b/sync-for-expenses/src/codat_sync_for_expenses/api/transaction_status.py new file mode 100644 index 000000000..3243ab877 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/api/transaction_status.py @@ -0,0 +1,506 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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 List, Optional +from typing_extensions import Annotated +from codat_sync_for_expenses.models.shared.companies import Companies +from codat_sync_for_expenses.models.shared.connections import Connections +from codat_sync_for_expenses.models.shared.contact import Contact +from codat_sync_for_expenses.models.shared.customers import Customers +from codat_sync_for_expenses.models.shared.suppliers import Suppliers +from codat_sync_for_expenses.models.transaction import Transaction +from codat_sync_for_expenses.models.shared.schema_transaction import SchemaTransaction +from codat_sync_for_expenses.models.shared.transactions import Transactions + +from codat_sync_for_expenses.api_client import ApiClient, RequestSerialized +from codat_sync_for_expenses.api_response import ApiResponse +from codat_sync_for_expenses.exceptions import ApiException +from codat_sync_for_expenses.models.errors import ErrorMessage, SDKError +from codat_sync_for_expenses.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_sync_for_expenses.rest import RESTResponseType +from codat_sync_for_expenses.types import UNSET, OptionalNullable +from codat_sync_for_expenses.utils.retries import RetryConfig, execute_with_retries + + +class GetSyncTransactionRequestTypedDict(TypedDict): + """TypedDict variant of GetSyncTransactionRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + sync_id: Annotated[str, Field(description="Unique identifier for a sync.")] + transaction_id: Annotated[str, Field(description="The unique identifier for your SMB's transaction.")] + + +class GetSyncTransactionRequest(BaseModel): + """Request envelope for get_sync_transaction.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + sync_id: Annotated[str, Field(description="Unique identifier for a sync.")] + transaction_id: Annotated[str, Field(description="The unique identifier for your SMB's transaction.")] + + @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 ListSyncTransactionsRequestTypedDict(TypedDict): + """TypedDict variant of ListSyncTransactionsRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + sync_id: Annotated[str, Field(description="Unique identifier for a sync.")] + 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).")]] + + +class ListSyncTransactionsRequest(BaseModel): + """Request envelope for list_sync_transactions.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + sync_id: Annotated[str, Field(description="Unique identifier for a sync.")] + 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 + + @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 TransactionStatus: + """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['GetSyncTransactionRequest', 'GetSyncTransactionRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> List[SchemaTransaction]: + """Get sync transaction""" # noqa: E501 + + if isinstance(request, dict): + request = GetSyncTransactionRequest.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_sync_transaction_serialize( + company_id=request.company_id, + sync_id=request.sync_id, + transaction_id=request.transaction_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[SchemaTransaction]", + '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-sync-transaction', + ) + 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['GetSyncTransactionRequest', 'GetSyncTransactionRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> List[SchemaTransaction]: + 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_sync_transaction_serialize( + self, + company_id, + sync_id, + transaction_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 sync_id is not None: + _path_params['syncId'] = sync_id + if transaction_id is not None: + _path_params['transactionId'] = transaction_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}/sync/expenses/syncs/{syncId}/transactions/{transactionId}', + 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['ListSyncTransactionsRequest', 'ListSyncTransactionsRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Transactions: + """List sync transactions""" # noqa: E501 + + if isinstance(request, dict): + request = ListSyncTransactionsRequest.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_sync_transactions_serialize( + company_id=request.company_id, + sync_id=request.sync_id, + page=request.page, + page_size=request.page_size, + _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': "Transactions", + '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-sync-transactions', + ) + 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['ListSyncTransactionsRequest', 'ListSyncTransactionsRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> Transactions: + 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_sync_transactions_serialize( + self, + company_id, + sync_id, + page, + page_size, + _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 sync_id is not None: + _path_params['syncId'] = sync_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)) + + # 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}/sync/expenses/syncs/{syncId}/transactions', + 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-expenses/src/codat_sync_for_expenses/api/transfers.py b/sync-for-expenses/src/codat_sync_for_expenses/api/transfers.py new file mode 100644 index 000000000..1ffce909a --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/api/transfers.py @@ -0,0 +1,287 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.models.shared.companies import Companies +from codat_sync_for_expenses.models.shared.connections import Connections +from codat_sync_for_expenses.models.shared.contact import Contact +from codat_sync_for_expenses.models.shared.customers import Customers +from codat_sync_for_expenses.models.shared.suppliers import Suppliers +from codat_sync_for_expenses.models.transaction import Transaction +from codat_sync_for_expenses.models.shared.transfertransactionrequest import TransferTransactionRequest +from codat_sync_for_expenses.models.shared.transfertransactionresponse import TransferTransactionResponse + +from codat_sync_for_expenses.api_client import ApiClient, RequestSerialized +from codat_sync_for_expenses.api_response import ApiResponse +from codat_sync_for_expenses.exceptions import ApiException +from codat_sync_for_expenses.models.errors import ErrorMessage, SDKError +from codat_sync_for_expenses.models.errors.errormessage import ErrorMessageData as _ErrorMessageDataSchema +from codat_sync_for_expenses.rest import RESTResponseType +from codat_sync_for_expenses.types import UNSET, OptionalNullable +from codat_sync_for_expenses.utils.retries import RetryConfig, execute_with_retries + + +class CreateTransferTransactionRequestTypedDict(TypedDict): + """TypedDict variant of CreateTransferTransactionRequest, for dict-literal request inputs.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + transaction_id: Annotated[str, Field(description="The unique identifier for your SMB's transaction.")] + transfer_transaction_request: NotRequired[Optional[TransferTransactionRequest]] + + +class CreateTransferTransactionRequest(BaseModel): + """Request envelope for create_transfer_transaction.""" + company_id: Annotated[str, Field(description="Unique identifier for a company.")] + transaction_id: Annotated[str, Field(description="The unique identifier for your SMB's transaction.")] + transfer_transaction_request: Optional[TransferTransactionRequest] = 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 Transfers: + """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['CreateTransferTransactionRequest', 'CreateTransferTransactionRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> TransferTransactionResponse: + """Create transfer transaction""" # noqa: E501 + + if isinstance(request, dict): + request = CreateTransferTransactionRequest.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_transfer_transaction_serialize( + company_id=request.company_id, + transaction_id=request.transaction_id, + transfer_transaction_request=request.transfer_transaction_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': "TransferTransactionResponse", + '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-transfer-transaction', + ) + 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['CreateTransferTransactionRequest', 'CreateTransferTransactionRequestTypedDict'], + retries: OptionalNullable[RetryConfig] = UNSET, + server_url: Optional[str] = None, + timeout_ms: Optional[int] = None, + http_headers: Optional[Mapping[str, str]] = None, + ) -> TransferTransactionResponse: + 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_transfer_transaction_serialize( + self, + company_id, + transaction_id, + transfer_transaction_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 + if transaction_id is not None: + _path_params['transactionId'] = transaction_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if transfer_transaction_request is not None: + _body_params = transfer_transaction_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='PUT', + resource_path='/companies/{companyId}/sync/expenses/transfer-transactions/{transactionId}', + 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-expenses/src/codat_sync_for_expenses/api_client.py b/sync-for-expenses/src/codat_sync_for_expenses/api_client.py new file mode 100644 index 000000000..13c206dd8 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/api_client.py @@ -0,0 +1,803 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.configuration import Configuration +from codat_sync_for_expenses.api_response import ApiResponse, T as ApiResponseT +import codat_sync_for_expenses.models +from codat_sync_for_expenses import rest +from codat_sync_for_expenses.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_expenses.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-expenses/src/codat_sync_for_expenses/api_response.py b/sync-for-expenses/src/codat_sync_for_expenses/api_response.py new file mode 100644 index 000000000..8a1236a62 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/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-expenses/src/codat_sync_for_expenses/attachments.py b/sync-for-expenses/src/codat_sync_for_expenses/attachments.py index 7838d7242..1759989fc 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/attachments.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/attachments.py @@ -1,261 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.attachments — re-export of the attachments method group.""" -from .basesdk import BaseSDK -from codat_sync_for_expenses import utils -from codat_sync_for_expenses._hooks import HookContext -from codat_sync_for_expenses.models import errors, operations, shared -from codat_sync_for_expenses.types import BaseModel, OptionalNullable, UNSET -from codat_sync_for_expenses.utils.unmarshal_json_response import ( - unmarshal_json_response, -) -from typing import Any, Mapping, Optional, Union, cast - - -class Attachments(BaseSDK): - r"""Attach receipts to a transaction for a complete audit trail.""" - - def upload( - self, - *, - request: Union[ - operations.UploadExpenseAttachmentRequest, - operations.UploadExpenseAttachmentRequestTypedDict, - ], - 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 attachment - - The *Upload attachment* endpoint uploads an attachment in the accounting software against the given transactionId. - - [Expense transactions](https://docs.codat.io/sync-for-expenses-api#/schemas/ExpenseTransaction) represent transactions made with a company debit or credit card. Attachments for `Adjustment` and `Transfer` transaction types are not supported for any integrations. - - **Integration-specific behavior** - - Each accounting software supports different file formats and sizes. - - | Integration | File size | File extension | Supported transactions | - |-----------------------------------|-----------|-------------------------------------------------------|------------------------| - | **Xero** | 3 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 | All supported types | - | **QuickBooks Online** | 100 MB | AI, CSV, DOC, DOCX, EPS, GIF, JPEG, JPG, ODS, PAGES, PDF, PNG, RTF, TIF, TXT, XLS, XLSX, XML | `expense-transactions.Payment`, `expense-transactions.Refund`, `reimbursable-expense-transactions` | - | **NetSuite** | 100 MB | BMP, CSV, XLS, XLSX, JSON, PDF, PJPG, PJPEG, PNG, TXT, SVG, TIF, TIFF, DOC, DOCX, ZIP |`expense-transactions.Payment`, `expense-transactions.Refund` | - | **Dynamics 365 Business Central** | 350 MB | [No explicit requirements outlined](https://learn.microsoft.com/en-gb/dynamics365/business-central/ui-how-add-link-to-record#to-attach-a-file-to-a-purchase-invoice) for text, image, and video files. | All supported types - | **QuickBooks Desktop** | NA | Does not support attachment upload | N/A | - | **FreeAgent** | 5MB | PNG, X-PNG, JPEG, PJG, GIF, X-PDF | `expense-transactions.Payment`, `reimbursable-expense-transactions` - | **Zoho Books** | 5MB | GIF, PNG, JPEG, JPG, BMP, PDF | `expense-transactions.Payment`, `reimbursable-expense-transactions` | - - :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.UploadExpenseAttachmentRequest - ) - request = cast(operations.UploadExpenseAttachmentRequest, request) - - req = self._build_request( - method="POST", - path="/companies/{companyId}/sync/expenses/syncs/{syncId}/transactions/{transactionId}/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-expense-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, "200", "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_async( - self, - *, - request: Union[ - operations.UploadExpenseAttachmentRequest, - operations.UploadExpenseAttachmentRequestTypedDict, - ], - 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 attachment - - The *Upload attachment* endpoint uploads an attachment in the accounting software against the given transactionId. - - [Expense transactions](https://docs.codat.io/sync-for-expenses-api#/schemas/ExpenseTransaction) represent transactions made with a company debit or credit card. Attachments for `Adjustment` and `Transfer` transaction types are not supported for any integrations. - - **Integration-specific behavior** - - Each accounting software supports different file formats and sizes. - - | Integration | File size | File extension | Supported transactions | - |-----------------------------------|-----------|-------------------------------------------------------|------------------------| - | **Xero** | 3 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 | All supported types | - | **QuickBooks Online** | 100 MB | AI, CSV, DOC, DOCX, EPS, GIF, JPEG, JPG, ODS, PAGES, PDF, PNG, RTF, TIF, TXT, XLS, XLSX, XML | `expense-transactions.Payment`, `expense-transactions.Refund`, `reimbursable-expense-transactions` | - | **NetSuite** | 100 MB | BMP, CSV, XLS, XLSX, JSON, PDF, PJPG, PJPEG, PNG, TXT, SVG, TIF, TIFF, DOC, DOCX, ZIP |`expense-transactions.Payment`, `expense-transactions.Refund` | - | **Dynamics 365 Business Central** | 350 MB | [No explicit requirements outlined](https://learn.microsoft.com/en-gb/dynamics365/business-central/ui-how-add-link-to-record#to-attach-a-file-to-a-purchase-invoice) for text, image, and video files. | All supported types - | **QuickBooks Desktop** | NA | Does not support attachment upload | N/A | - | **FreeAgent** | 5MB | PNG, X-PNG, JPEG, PJG, GIF, X-PDF | `expense-transactions.Payment`, `reimbursable-expense-transactions` - | **Zoho Books** | 5MB | GIF, PNG, JPEG, JPG, BMP, PDF | `expense-transactions.Payment`, `reimbursable-expense-transactions` | - - :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.UploadExpenseAttachmentRequest - ) - request = cast(operations.UploadExpenseAttachmentRequest, request) - - req = self._build_request_async( - method="POST", - path="/companies/{companyId}/sync/expenses/syncs/{syncId}/transactions/{transactionId}/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-expense-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, "200", "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) +from codat_sync_for_expenses.api.attachments import Attachments diff --git a/sync-for-expenses/src/codat_sync_for_expenses/bank_accounts.py b/sync-for-expenses/src/codat_sync_for_expenses/bank_accounts.py index 9a9bb7bd7..a50d4b6fa 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/bank_accounts.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/bank_accounts.py @@ -1,451 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.bank_accounts — re-export of the bank_accounts method group.""" -from .basesdk import BaseSDK -from codat_sync_for_expenses import utils -from codat_sync_for_expenses._hooks import HookContext -from codat_sync_for_expenses.models import errors, operations, shared -from codat_sync_for_expenses.types import BaseModel, OptionalNullable, UNSET -from codat_sync_for_expenses.utils.unmarshal_json_response import ( - unmarshal_json_response, -) -from typing import Any, Mapping, Optional, Union, cast - - -class BankAccounts(BaseSDK): - r"""Create bank accounts and view create bank account options.""" - - 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.CreateBankAccountResponse: - r"""Create bank account - - The *Create bank account* endpoint creates a new [bank account](https://docs.codat.io/sync-for-expenses-api#/schemas/BankAccount) for a given company's connection. - - [Bank accounts](https://docs.codat.io/sync-for-expenses-api#/schemas/BankAccount) are financial accounts maintained by a bank or other financial institution. - - **Integration-specific behavior** - - Required data may vary by integration. To see what data to post, first call [Get create/update bank account model](https://docs.codat.io/sync-for-expenses-api#/operations/get-create-update-bankAccounts-model). - - :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}/push/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 if request is not None else None, - True, - True, - "json", - OptionalNullable[shared.BankAccount], - ), - 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, "200", "application/json"): - return unmarshal_json_response(shared.CreateBankAccountResponse, 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.CreateBankAccountResponse: - r"""Create bank account - - The *Create bank account* endpoint creates a new [bank account](https://docs.codat.io/sync-for-expenses-api#/schemas/BankAccount) for a given company's connection. - - [Bank accounts](https://docs.codat.io/sync-for-expenses-api#/schemas/BankAccount) are financial accounts maintained by a bank or other financial institution. - - **Integration-specific behavior** - - Required data may vary by integration. To see what data to post, first call [Get create/update bank account model](https://docs.codat.io/sync-for-expenses-api#/operations/get-create-update-bankAccounts-model). - - :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}/push/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 if request is not None else None, - True, - True, - "json", - OptionalNullable[shared.BankAccount], - ), - 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, "200", "application/json"): - return unmarshal_json_response(shared.CreateBankAccountResponse, 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 get_create_model( - self, - *, - request: Union[ - operations.GetCreateBankAccountsModelRequest, - operations.GetCreateBankAccountsModelRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.PushOption: - r"""Get create bank account model - - The *Get create/update bank account model* endpoint returns the expected data for the request payload when creating and updating a [bank account](https://docs.codat.io/sync-for-expenses-api#/schemas/BankAccount) for a given company and integration. - - [Bank accounts](https://docs.codat.io/sync-for-expenses-api#/schemas/BankAccount) are financial accounts maintained by a bank or other financial institution. - - **Integration-specific behavior** - - See the *response examples* for integration-specific indicative models. - - - :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.GetCreateBankAccountsModelRequest - ) - request = cast(operations.GetCreateBankAccountsModelRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/connections/{connectionId}/options/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, - 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-create-bankAccounts-model", - 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.PushOption, 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_create_model_async( - self, - *, - request: Union[ - operations.GetCreateBankAccountsModelRequest, - operations.GetCreateBankAccountsModelRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.PushOption: - r"""Get create bank account model - - The *Get create/update bank account model* endpoint returns the expected data for the request payload when creating and updating a [bank account](https://docs.codat.io/sync-for-expenses-api#/schemas/BankAccount) for a given company and integration. - - [Bank accounts](https://docs.codat.io/sync-for-expenses-api#/schemas/BankAccount) are financial accounts maintained by a bank or other financial institution. - - **Integration-specific behavior** - - See the *response examples* for integration-specific indicative models. - - - :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.GetCreateBankAccountsModelRequest - ) - request = cast(operations.GetCreateBankAccountsModelRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/connections/{connectionId}/options/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, - 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-create-bankAccounts-model", - 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.PushOption, 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_expenses.api.bank_accounts import BankAccounts diff --git a/sync-for-expenses/src/codat_sync_for_expenses/basesdk.py b/sync-for-expenses/src/codat_sync_for_expenses/basesdk.py deleted file mode 100644 index f4d1f7647..000000000 --- a/sync-for-expenses/src/codat_sync_for_expenses/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_expenses import utils -from codat_sync_for_expenses._hooks import ( - AfterErrorContext, - AfterSuccessContext, - BeforeRequestContext, - HookContext, -) -from codat_sync_for_expenses.models import errors -from codat_sync_for_expenses.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-expenses/src/codat_sync_for_expenses/companies.py b/sync-for-expenses/src/codat_sync_for_expenses/companies.py index 9e5e6957f..91dcd0486 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/companies.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/companies.py @@ -1,1285 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.companies — re-export of the companies method group.""" -from .basesdk import BaseSDK -from codat_sync_for_expenses import utils -from codat_sync_for_expenses._hooks import HookContext -from codat_sync_for_expenses.models import errors, operations, shared -from codat_sync_for_expenses.types import BaseModel, OptionalNullable, UNSET -from codat_sync_for_expenses.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 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-expenses-api#/schemas/Company) that represents your customer in Codat. - - A [company](https://docs.codat.io/sync-for-expenses-api#/schemas/Company) represents a business sharing access to their data. - Each company can have multiple [connections](https://docs.codat.io/sync-for-expenses-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-expenses-api#/schemas/Company) that represents your customer in Codat. - - A [company](https://docs.codat.io/sync-for-expenses-api#/schemas/Company) represents a business sharing access to their data. - Each company can have multiple [connections](https://docs.codat.io/sync-for-expenses-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 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-expenses-api#/schemas/Company), its [connections](https://docs.codat.io/sync-for-expenses-api#/schemas/Connection) and any cached data. This operation is irreversible. - - A [company](https://docs.codat.io/sync-for-expenses-api#/schemas/Company) represents a business sharing access to their data. - Each company can have multiple [connections](https://docs.codat.io/sync-for-expenses-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-expenses-api#/schemas/Company), its [connections](https://docs.codat.io/sync-for-expenses-api#/schemas/Connection) and any cached data. This operation is irreversible. - - A [company](https://docs.codat.io/sync-for-expenses-api#/schemas/Company) represents a business sharing access to their data. - Each company can have multiple [connections](https://docs.codat.io/sync-for-expenses-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-expenses-api#/schemas/Company) represents a business sharing access to their data. - Each company can have multiple [connections](https://docs.codat.io/sync-for-expenses-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-expenses-api#/schemas/Company) represents a business sharing access to their data. - Each company can have multiple [connections](https://docs.codat.io/sync-for-expenses-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) - - 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-expenses-api#/schemas/Company) associated to your instances. - - A [company](https://docs.codat.io/sync-for-expenses-api#/schemas/Company) represents a business sharing access to their data. - Each company can have multiple [connections](https://docs.codat.io/sync-for-expenses-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-expenses-api#/schemas/Company) associated to your instances. - - A [company](https://docs.codat.io/sync-for-expenses-api#/schemas/Company) represents a business sharing access to their data. - Each company can have multiple [connections](https://docs.codat.io/sync-for-expenses-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 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-expenses-api#/schemas/Company) represents a business sharing access to their data. - Each company can have multiple [connections](https://docs.codat.io/sync-for-expenses-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-expenses-api#/schemas/Company) represents a business sharing access to their data. - Each company can have multiple [connections](https://docs.codat.io/sync-for-expenses-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-expenses-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-expenses-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) +from codat_sync_for_expenses.api.companies import Companies diff --git a/sync-for-expenses/src/codat_sync_for_expenses/company_info.py b/sync-for-expenses/src/codat_sync_for_expenses/company_info.py index ffb248d4b..5ff016acc 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/company_info.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/company_info.py @@ -1,209 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.company_info — re-export of the company_info method group.""" -from .basesdk import BaseSDK -from codat_sync_for_expenses import utils -from codat_sync_for_expenses._hooks import HookContext -from codat_sync_for_expenses.models import errors, operations, shared -from codat_sync_for_expenses.types import BaseModel, OptionalNullable, UNSET -from codat_sync_for_expenses.utils.unmarshal_json_response import ( - unmarshal_json_response, -) -from typing import Any, Mapping, Optional, Union, cast - - -class CompanyInfo(BaseSDK): - r"""View the company information of your customers' linked accounting software.""" - - def get( - self, - *, - request: Union[ - operations.GetCompanyInfoRequest, operations.GetCompanyInfoRequestTypedDict - ], - 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 info - - Gets the latest basic info 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.GetCompanyInfoRequest) - request = cast(operations.GetCompanyInfoRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/data/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-info", - 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, ["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 get_async( - self, - *, - request: Union[ - operations.GetCompanyInfoRequest, operations.GetCompanyInfoRequestTypedDict - ], - 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 info - - Gets the latest basic info 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.GetCompanyInfoRequest) - request = cast(operations.GetCompanyInfoRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/data/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-info", - 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, ["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_expenses.api.company_info import CompanyInfo diff --git a/sync-for-expenses/src/codat_sync_for_expenses/configuration.py b/sync-for-expenses/src/codat_sync_for_expenses/configuration.py index c2a5f51b1..9db135735 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/configuration.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/configuration.py @@ -1,429 +1,596 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from .basesdk import BaseSDK -from codat_sync_for_expenses import utils -from codat_sync_for_expenses._hooks import HookContext -from codat_sync_for_expenses.models import errors, operations, shared -from codat_sync_for_expenses.types import BaseModel, OptionalNullable, UNSET -from codat_sync_for_expenses.utils.unmarshal_json_response import ( - unmarshal_json_response, +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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, + }, ) -from typing import Any, Mapping, Optional, Union, cast -class Configuration(BaseSDK): - r"""View and manage mapping configuration and defaults for expense transactions.""" +OAuth2AuthSetting = TypedDict( + "OAuth2AuthSetting", + { + "type": Literal["oauth2"], + "in": Literal["header"], + "key": Literal["Authorization"], + "value": str, + }, +) - def get( - self, - *, - request: Union[ - operations.GetCompanyConfigurationRequest, - operations.GetCompanyConfigurationRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.CompanyConfiguration: - r"""Get company configuration - - Gets a company's expense sync configuration - - :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.GetCompanyConfigurationRequest - ) - request = cast(operations.GetCompanyConfigurationRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/sync/expenses/config", - 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-configuration", - 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.CompanyConfiguration, 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( + +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_expenses.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, *, - request: Union[ - operations.GetCompanyConfigurationRequest, - operations.GetCompanyConfigurationRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.CompanyConfiguration: - r"""Get company configuration - - Gets a company's expense sync configuration - - :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 + 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_expenses") + 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: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal( - request, operations.GetCompanyConfigurationRequest - ) - request = cast(operations.GetCompanyConfigurationRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/sync/expenses/config", - 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-configuration", - 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.CompanyConfiguration, 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 set( - self, - *, - request: Union[ - operations.SetCompanyConfigurationRequest, - operations.SetCompanyConfigurationRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.CompanyConfiguration: - r"""Set company configuration - - Sets a company's expense sync configuration - - :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 + 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: - base_url = self._get_url(base_url, url_variables) - - if not isinstance(request, BaseModel): - request = utils.unmarshal( - request, operations.SetCompanyConfigurationRequest - ) - request = cast(operations.SetCompanyConfigurationRequest, request) - - req = self._build_request( - method="POST", - path="/companies/{companyId}/sync/expenses/config", - 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_configuration if request is not None else None, - False, - True, - "json", - Optional[shared.CompanyConfiguration], - ), - 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 + # 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: - 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="set-company-configuration", - 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.CompanyConfiguration, 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 set_async( + 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: prealpha\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': "No description provided", + } + ] + + def get_host_from_settings( self, - *, - request: Union[ - operations.SetCompanyConfigurationRequest, - operations.SetCompanyConfigurationRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.CompanyConfiguration: - r"""Set company configuration - - Sets a company's expense sync configuration - - :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.SetCompanyConfigurationRequest - ) - request = cast(operations.SetCompanyConfigurationRequest, request) - - req = self._build_request_async( - method="POST", - path="/companies/{companyId}/sync/expenses/config", - 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_configuration if request is not None else None, - False, - True, - "json", - Optional[shared.CompanyConfiguration], - ), - 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="set-company-configuration", - 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.CompanyConfiguration, 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) + 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-expenses/src/codat_sync_for_expenses/connections.py b/sync-for-expenses/src/codat_sync_for_expenses/connections.py index 9fa7bedf9..20a67dfeb 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/connections.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/connections.py @@ -1,1227 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.connections — re-export of the connections method group.""" -from .basesdk import BaseSDK -from codat_sync_for_expenses import utils -from codat_sync_for_expenses._hooks import HookContext -from codat_sync_for_expenses.models import errors, operations, shared -from codat_sync_for_expenses.types import BaseModel, OptionalNullable, UNSET -from codat_sync_for_expenses.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 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 create_partner_expense_connection( - self, - *, - request: Union[ - operations.CreatePartnerExpenseConnectionRequest, - operations.CreatePartnerExpenseConnectionRequestTypedDict, - ], - 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 partner expense connection - - Creates a partner expense data connection - - :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.CreatePartnerExpenseConnectionRequest - ) - request = cast(operations.CreatePartnerExpenseConnectionRequest, request) - - req = self._build_request( - method="POST", - path="/companies/{companyId}/sync/expenses/connections/partnerExpense", - 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="create-partner-expense-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, ["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_partner_expense_connection_async( - self, - *, - request: Union[ - operations.CreatePartnerExpenseConnectionRequest, - operations.CreatePartnerExpenseConnectionRequestTypedDict, - ], - 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 partner expense connection - - Creates a partner expense data connection - - :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.CreatePartnerExpenseConnectionRequest - ) - request = cast(operations.CreatePartnerExpenseConnectionRequest, request) - - req = self._build_request_async( - method="POST", - path="/companies/{companyId}/sync/expenses/connections/partnerExpense", - 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="create-partner-expense-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, ["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 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 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 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 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_expenses.api.connections import Connections diff --git a/sync-for-expenses/src/codat_sync_for_expenses/customers.py b/sync-for-expenses/src/codat_sync_for_expenses/customers.py index fd58f3fbc..5604e21d8 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/customers.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/customers.py @@ -1,867 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.customers — re-export of the customers method group.""" -from .basesdk import BaseSDK -from codat_sync_for_expenses import utils -from codat_sync_for_expenses._hooks import HookContext -from codat_sync_for_expenses.models import errors, operations, shared -from codat_sync_for_expenses.types import BaseModel, OptionalNullable, UNSET -from codat_sync_for_expenses.utils.unmarshal_json_response import ( - unmarshal_json_response, -) -from typing import Any, Mapping, Optional, Union, cast - - -class Customers(BaseSDK): - r"""Get, create, and update customers.""" - - def create( - self, - *, - request: Union[ - operations.CreateCustomerRequest, operations.CreateCustomerRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.CreateCustomerResponse: - r"""Create customer - - The *Create customer* endpoint creates a new [customer](https://docs.codat.io/sync-for-expenses-api#/schemas/Customer) for a given company's connection. - - [Customers](https://docs.codat.io/sync-for-expenses-api#/schemas/Customer) are people or organizations that buy goods or services from the SMB. - - **Integration-specific behavior** - - Required data may vary by integration. To see what data to post, first call [Get create/update customer model](https://docs.codat.io/sync-for-expenses-api#/operations/get-create-update-customers-model). - - :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.CreateCustomerRequest) - request = cast(operations.CreateCustomerRequest, request) - - req = self._build_request( - method="POST", - path="/companies/{companyId}/connections/{connectionId}/push/customers", - 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.customer if request is not None else None, - True, - True, - "json", - OptionalNullable[shared.Customer], - ), - 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-customer", - 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.CreateCustomerResponse, 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.CreateCustomerRequest, operations.CreateCustomerRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.CreateCustomerResponse: - r"""Create customer - - The *Create customer* endpoint creates a new [customer](https://docs.codat.io/sync-for-expenses-api#/schemas/Customer) for a given company's connection. - - [Customers](https://docs.codat.io/sync-for-expenses-api#/schemas/Customer) are people or organizations that buy goods or services from the SMB. - - **Integration-specific behavior** - - Required data may vary by integration. To see what data to post, first call [Get create/update customer model](https://docs.codat.io/sync-for-expenses-api#/operations/get-create-update-customers-model). - - :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.CreateCustomerRequest) - request = cast(operations.CreateCustomerRequest, request) - - req = self._build_request_async( - method="POST", - path="/companies/{companyId}/connections/{connectionId}/push/customers", - 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.customer if request is not None else None, - True, - True, - "json", - OptionalNullable[shared.Customer], - ), - 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-customer", - 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.CreateCustomerResponse, 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 get( - self, - *, - request: Union[ - operations.GetCustomerRequest, operations.GetCustomerRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Customer: - r"""Get customer - - The *Get customer* endpoint returns a single customer for a given customerId. - - [Customers](https://docs.codat.io/sync-for-expenses-api#/schemas/Customer) are people or organizations that buy goods or services from the SMB. - - Before using this endpoint, you must have [retrieved data for the company](https://docs.codat.io/sync-for-expenses-api#/operations/refresh-company-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.GetCustomerRequest) - request = cast(operations.GetCustomerRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/data/customers/{customerId}", - 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-customer", - 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.Customer, 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 get_async( - self, - *, - request: Union[ - operations.GetCustomerRequest, operations.GetCustomerRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Customer: - r"""Get customer - - The *Get customer* endpoint returns a single customer for a given customerId. - - [Customers](https://docs.codat.io/sync-for-expenses-api#/schemas/Customer) are people or organizations that buy goods or services from the SMB. - - Before using this endpoint, you must have [retrieved data for the company](https://docs.codat.io/sync-for-expenses-api#/operations/refresh-company-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.GetCustomerRequest) - request = cast(operations.GetCustomerRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/data/customers/{customerId}", - 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-customer", - 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.Customer, 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 list( - self, - *, - request: Union[ - operations.ListCustomersRequest, operations.ListCustomersRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Customers: - r"""List customers - - The *List customers* endpoint returns a list of [customers](https://docs.codat.io/sync-for-expenses-api#/schemas/Customer) for a given company's connection. - - [Customers](https://docs.codat.io/sync-for-expenses-api#/schemas/Customer) are people or organizations that buy goods or services from the SMB. - - Before using this endpoint, you must have [retrieved data for the company](https://docs.codat.io/sync-for-expenses-api#/operations/refresh-company-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.ListCustomersRequest) - request = cast(operations.ListCustomersRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/data/customers", - 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-customers", - 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.Customers, 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.ListCustomersRequest, operations.ListCustomersRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Customers: - r"""List customers - - The *List customers* endpoint returns a list of [customers](https://docs.codat.io/sync-for-expenses-api#/schemas/Customer) for a given company's connection. - - [Customers](https://docs.codat.io/sync-for-expenses-api#/schemas/Customer) are people or organizations that buy goods or services from the SMB. - - Before using this endpoint, you must have [retrieved data for the company](https://docs.codat.io/sync-for-expenses-api#/operations/refresh-company-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.ListCustomersRequest) - request = cast(operations.ListCustomersRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/data/customers", - 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-customers", - 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.Customers, 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.UpdateCustomerRequest, operations.UpdateCustomerRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.UpdateCustomerResponse: - r"""Update customer - - The *Update customer* endpoint updates an existing [customer](https://docs.codat.io/sync-for-expenses-api#/schemas/Customer) for a given company's connection. - - [Customers](https://docs.codat.io/sync-for-expenses-api#/schemas/Customer) are people or organizations that buy goods or services from the SMB. - - **Integration-specific behavior** - - Required data may vary by integration. To see what data to post, first call [Get create/update customer model](https://docs.codat.io/sync-for-expenses-api#/operations/get-create-update-customers-model). - - :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.UpdateCustomerRequest) - request = cast(operations.UpdateCustomerRequest, request) - - req = self._build_request( - method="PUT", - path="/companies/{companyId}/connections/{connectionId}/push/customers/{customerId}", - 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.customer if request is not None else None, - True, - True, - "json", - OptionalNullable[shared.Customer], - ), - 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-customer", - 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.UpdateCustomerResponse, 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.UpdateCustomerRequest, operations.UpdateCustomerRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.UpdateCustomerResponse: - r"""Update customer - - The *Update customer* endpoint updates an existing [customer](https://docs.codat.io/sync-for-expenses-api#/schemas/Customer) for a given company's connection. - - [Customers](https://docs.codat.io/sync-for-expenses-api#/schemas/Customer) are people or organizations that buy goods or services from the SMB. - - **Integration-specific behavior** - - Required data may vary by integration. To see what data to post, first call [Get create/update customer model](https://docs.codat.io/sync-for-expenses-api#/operations/get-create-update-customers-model). - - :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.UpdateCustomerRequest) - request = cast(operations.UpdateCustomerRequest, request) - - req = self._build_request_async( - method="PUT", - path="/companies/{companyId}/connections/{connectionId}/push/customers/{customerId}", - 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.customer if request is not None else None, - True, - True, - "json", - OptionalNullable[shared.Customer], - ), - 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-customer", - 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.UpdateCustomerResponse, 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_expenses.api.customers import Customers diff --git a/sync-for-expenses/src/codat_sync_for_expenses/exceptions.py b/sync-for-expenses/src/codat_sync_for_expenses/exceptions.py new file mode 100644 index 000000000..0ba2a424b --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/exceptions.py @@ -0,0 +1,200 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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-expenses/src/codat_sync_for_expenses/expenses.py b/sync-for-expenses/src/codat_sync_for_expenses/expenses.py index 985549d7c..7865fcf57 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/expenses.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/expenses.py @@ -1,519 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.expenses — re-export of the expenses method group.""" -from .basesdk import BaseSDK -from codat_sync_for_expenses import utils -from codat_sync_for_expenses._hooks import HookContext -from codat_sync_for_expenses.models import errors, operations, shared -from codat_sync_for_expenses.types import BaseModel, OptionalNullable, UNSET -from codat_sync_for_expenses.utils.unmarshal_json_response import ( - unmarshal_json_response, -) -from typing import Any, List, Mapping, Optional, Union, cast - - -class Expenses(BaseSDK): - r"""Create and update transactions that represent your customers' spend.""" - - def create( - self, - *, - request: Union[ - operations.CreateExpenseTransactionRequest, - operations.CreateExpenseTransactionRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.CreateExpenseResponse: - r"""Create expense transaction - - The *Create expense* endpoint creates an [expense transaction](https://docs.codat.io/sync-for-expenses-api#/schemas/ExpenseTransaction) in the accounting software for a given company's connection. - - [Expense transactions](https://docs.codat.io/sync-for-expenses-api#/schemas/ExpenseTransaction) represent transactions made with a company debit or credit card. - - ### Supported Integrations - - | Integration | Supported | - |-------------------------------|-----------| - | Dynamics 365 Business Central | Yes | - | FreeAgent | Yes | - | QuickBooks Desktop | Yes | - | QuickBooks Online | Yes | - | Oracle NetSuite | Yes | - | Sage Intacct | Yes | - | Xero | 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.CreateExpenseTransactionRequest - ) - request = cast(operations.CreateExpenseTransactionRequest, request) - - req = self._build_request( - method="POST", - path="/companies/{companyId}/sync/expenses/expense-transactions", - 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[List[shared.ExpenseTransaction]], - ), - 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-expense-transaction", - 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.CreateExpenseResponse, 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.CreateExpenseTransactionRequest, - operations.CreateExpenseTransactionRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.CreateExpenseResponse: - r"""Create expense transaction - - The *Create expense* endpoint creates an [expense transaction](https://docs.codat.io/sync-for-expenses-api#/schemas/ExpenseTransaction) in the accounting software for a given company's connection. - - [Expense transactions](https://docs.codat.io/sync-for-expenses-api#/schemas/ExpenseTransaction) represent transactions made with a company debit or credit card. - - ### Supported Integrations - - | Integration | Supported | - |-------------------------------|-----------| - | Dynamics 365 Business Central | Yes | - | FreeAgent | Yes | - | QuickBooks Desktop | Yes | - | QuickBooks Online | Yes | - | Oracle NetSuite | Yes | - | Sage Intacct | Yes | - | Xero | 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.CreateExpenseTransactionRequest - ) - request = cast(operations.CreateExpenseTransactionRequest, request) - - req = self._build_request_async( - method="POST", - path="/companies/{companyId}/sync/expenses/expense-transactions", - 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[List[shared.ExpenseTransaction]], - ), - 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-expense-transaction", - 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.CreateExpenseResponse, 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.UpdateExpenseTransactionRequest, - operations.UpdateExpenseTransactionRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.UpdateExpenseResponse: - r"""Update expense transactions - - The *Update expense* endpoint updates an existing [expense transaction](https://docs.codat.io/sync-for-expenses-api#/schemas/UpdateExpenseRequest) in the accounting software for a given company's connection. - - [Expense transactions](https://docs.codat.io/sync-for-expenses-api#/schemas/UpdateExpenseRequest) represent transactions made with a company debit or credit card. - - ### Supported integrations - The following integrations are supported for the [Payment](https://docs.codat.io/expenses/sync-process/expense-transactions#transaction-types) transaction `type` only: - | Integration | Supported | - |-----------------------|-----------| - | FreeAgent | Yes | - | QuickBooks Desktop | Yes | - | QuickBooks Online | Yes | - | Oracle NetSuite | Yes | - | Sage Intacct | Yes | - | Xero | Yes | - | Zoho Books | Yes | - - #### Integration-specific behavior - - | Integration | Specifics | - |-----------------------|-----------| - | Sage Intacct | To sync **debit card expenses**, map the debit card to a Credit Card with the account type set to `Debit`.| - - :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.UpdateExpenseTransactionRequest - ) - request = cast(operations.UpdateExpenseTransactionRequest, request) - - req = self._build_request( - method="PUT", - path="/companies/{companyId}/sync/expenses/expense-transactions/{transactionId}", - 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.update_expense_request if request is not None else None, - False, - True, - "json", - Optional[shared.UpdateExpenseRequest], - ), - 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-expense-transaction", - 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, "202", "application/json"): - return unmarshal_json_response(shared.UpdateExpenseResponse, http_res) - if utils.match_response( - http_res, - ["400", "401", "402", "403", "404", "422", "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.UpdateExpenseTransactionRequest, - operations.UpdateExpenseTransactionRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.UpdateExpenseResponse: - r"""Update expense transactions - - The *Update expense* endpoint updates an existing [expense transaction](https://docs.codat.io/sync-for-expenses-api#/schemas/UpdateExpenseRequest) in the accounting software for a given company's connection. - - [Expense transactions](https://docs.codat.io/sync-for-expenses-api#/schemas/UpdateExpenseRequest) represent transactions made with a company debit or credit card. - - ### Supported integrations - The following integrations are supported for the [Payment](https://docs.codat.io/expenses/sync-process/expense-transactions#transaction-types) transaction `type` only: - | Integration | Supported | - |-----------------------|-----------| - | FreeAgent | Yes | - | QuickBooks Desktop | Yes | - | QuickBooks Online | Yes | - | Oracle NetSuite | Yes | - | Sage Intacct | Yes | - | Xero | Yes | - | Zoho Books | Yes | - - #### Integration-specific behavior - - | Integration | Specifics | - |-----------------------|-----------| - | Sage Intacct | To sync **debit card expenses**, map the debit card to a Credit Card with the account type set to `Debit`.| - - :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.UpdateExpenseTransactionRequest - ) - request = cast(operations.UpdateExpenseTransactionRequest, request) - - req = self._build_request_async( - method="PUT", - path="/companies/{companyId}/sync/expenses/expense-transactions/{transactionId}", - 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.update_expense_request if request is not None else None, - False, - True, - "json", - Optional[shared.UpdateExpenseRequest], - ), - 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-expense-transaction", - 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, "202", "application/json"): - return unmarshal_json_response(shared.UpdateExpenseResponse, http_res) - if utils.match_response( - http_res, - ["400", "401", "402", "403", "404", "422", "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_expenses.api.expenses import Expenses diff --git a/sync-for-expenses/src/codat_sync_for_expenses/manage_data.py b/sync-for-expenses/src/codat_sync_for_expenses/manage_data.py index 376c3b623..ef4a1f577 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/manage_data.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/manage_data.py @@ -1,1009 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.manage_data — re-export of the manage_data method group.""" -from .basesdk import BaseSDK -from codat_sync_for_expenses import utils -from codat_sync_for_expenses._hooks import HookContext -from codat_sync_for_expenses.models import errors, operations, shared -from codat_sync_for_expenses.types import BaseModel, OptionalNullable, UNSET -from codat_sync_for_expenses.utils.unmarshal_json_response import ( - unmarshal_json_response, -) -from typing import Any, Mapping, Optional, Union, cast - - -class ManageData(BaseSDK): - r"""Control and monitor the retrieval of data from an integration.""" - - def get( - self, - *, - request: Union[ - operations.GetDataStatusRequest, operations.GetDataStatusRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> operations.GetDataStatusDataStatuses: - r"""Get data status - - Get the state of each data type 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.GetDataStatusRequest) - request = cast(operations.GetDataStatusRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/dataStatus", - 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-data-status", - 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( - operations.GetDataStatusDataStatuses, 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.GetDataStatusRequest, operations.GetDataStatusRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> operations.GetDataStatusDataStatuses: - r"""Get data status - - Get the state of each data type 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.GetDataStatusRequest) - request = cast(operations.GetDataStatusRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/dataStatus", - 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-data-status", - 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( - operations.GetDataStatusDataStatuses, 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_pull_operation( - self, - *, - request: Union[ - operations.GetPullOperationRequest, - operations.GetPullOperationRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.PullOperation: - r"""Get pull operation - - Retrieve information about a single dataset or pull operation. - - :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.GetPullOperationRequest) - request = cast(operations.GetPullOperationRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/data/history/{datasetId}", - 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-pull-operation", - 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.PullOperation, 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_pull_operation_async( - self, - *, - request: Union[ - operations.GetPullOperationRequest, - operations.GetPullOperationRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.PullOperation: - r"""Get pull operation - - Retrieve information about a single dataset or pull operation. - - :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.GetPullOperationRequest) - request = cast(operations.GetPullOperationRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/data/history/{datasetId}", - 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-pull-operation", - 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.PullOperation, 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 list_pull_operations( - self, - *, - request: Union[ - operations.ListPullOperationsRequest, - operations.ListPullOperationsRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.PullOperations: - r"""List pull operations - - Gets the pull operation history (datasets) for a given 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.ListPullOperationsRequest) - request = cast(operations.ListPullOperationsRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/data/history", - 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-pull-operations", - 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.PullOperations, 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_pull_operations_async( - self, - *, - request: Union[ - operations.ListPullOperationsRequest, - operations.ListPullOperationsRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.PullOperations: - r"""List pull operations - - Gets the pull operation history (datasets) for a given 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.ListPullOperationsRequest) - request = cast(operations.ListPullOperationsRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/data/history", - 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-pull-operations", - 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.PullOperations, 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 refresh_all_data_types( - self, - *, - request: Union[ - operations.RefreshAllDataTypesRequest, - operations.RefreshAllDataTypesRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ): - r"""Refresh all data - - Refreshes all data types with `fetch on first link` set to `true` for a given company. - - This is an asynchronous operation, and will bring updated data into Codat from the linked integration for you to view. - - [Read more](https://docs.codat.io/core-concepts/data-type-settings) about data type settings and `fetch on first link`. - - :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.RefreshAllDataTypesRequest) - request = cast(operations.RefreshAllDataTypesRequest, request) - - req = self._build_request( - method="POST", - path="/companies/{companyId}/data/all", - 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="refresh-all-data-types", - 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, ["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 refresh_all_data_types_async( - self, - *, - request: Union[ - operations.RefreshAllDataTypesRequest, - operations.RefreshAllDataTypesRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ): - r"""Refresh all data - - Refreshes all data types with `fetch on first link` set to `true` for a given company. - - This is an asynchronous operation, and will bring updated data into Codat from the linked integration for you to view. - - [Read more](https://docs.codat.io/core-concepts/data-type-settings) about data type settings and `fetch on first link`. - - :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.RefreshAllDataTypesRequest) - request = cast(operations.RefreshAllDataTypesRequest, request) - - req = self._build_request_async( - method="POST", - path="/companies/{companyId}/data/all", - 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="refresh-all-data-types", - 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, ["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 refresh_data_type( - self, - *, - request: Union[ - operations.RefreshDataTypeRequest, - operations.RefreshDataTypeRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.PullOperation: - r"""Refresh data type - - Refreshes a given data type for a given company. - - This is an asynchronous operation, and will bring updated data into Codat from the linked integration for you to view. - - :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.RefreshDataTypeRequest) - request = cast(operations.RefreshDataTypeRequest, request) - - req = self._build_request( - method="POST", - path="/companies/{companyId}/data/queue/{dataType}", - 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="refresh-data-type", - 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.PullOperation, 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 refresh_data_type_async( - self, - *, - request: Union[ - operations.RefreshDataTypeRequest, - operations.RefreshDataTypeRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.PullOperation: - r"""Refresh data type - - Refreshes a given data type for a given company. - - This is an asynchronous operation, and will bring updated data into Codat from the linked integration for you to view. - - :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.RefreshDataTypeRequest) - request = cast(operations.RefreshDataTypeRequest, request) - - req = self._build_request_async( - method="POST", - path="/companies/{companyId}/data/queue/{dataType}", - 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="refresh-data-type", - 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.PullOperation, 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_expenses.api.manage_data import ManageData diff --git a/sync-for-expenses/src/codat_sync_for_expenses/mapping_options.py b/sync-for-expenses/src/codat_sync_for_expenses/mapping_options.py index 4e8b9a055..a0b872d81 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/mapping_options.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/mapping_options.py @@ -1,211 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.mapping_options — re-export of the mapping_options method group.""" -from .basesdk import BaseSDK -from codat_sync_for_expenses import utils -from codat_sync_for_expenses._hooks import HookContext -from codat_sync_for_expenses.models import errors, operations, shared -from codat_sync_for_expenses.types import BaseModel, OptionalNullable, UNSET -from codat_sync_for_expenses.utils.unmarshal_json_response import ( - unmarshal_json_response, -) -from typing import Any, Mapping, Optional, Union, cast - - -class MappingOptions(BaseSDK): - r"""Get accounts, trackingCategories and taxRates that can be used in your create and update requests.""" - - def get_mapping_options( - self, - *, - request: Union[ - operations.GetMappingOptionsRequest, - operations.GetMappingOptionsRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.MappingOptions: - r"""Mapping options - - Gets the mapping options (accounts, trackingCategories and taxRates) for a company's 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.GetMappingOptionsRequest) - request = cast(operations.GetMappingOptionsRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/sync/expenses/mappingOptions", - 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", - 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.MappingOptions, 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_mapping_options_async( - self, - *, - request: Union[ - operations.GetMappingOptionsRequest, - operations.GetMappingOptionsRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.MappingOptions: - r"""Mapping options - - Gets the mapping options (accounts, trackingCategories and taxRates) for a company's 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.GetMappingOptionsRequest) - request = cast(operations.GetMappingOptionsRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/sync/expenses/mappingOptions", - 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", - 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.MappingOptions, 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_expenses.api.mapping_options import MappingOptions diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/__init__.py b/sync-for-expenses/src/codat_sync_for_expenses/models/__init__.py index 3e68f3290..1a90bfb97 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/__init__.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/__init__.py @@ -1,23 +1,143 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from typing import Any, TYPE_CHECKING +# flake8: noqa +""" + Expenses -from codat_sync_for_expenses.utils.dynamic_imports import lazy_getattr, lazy_dir + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -if TYPE_CHECKING: - from . import errors, operations, shared + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.models.account import Account +from codat_sync_for_expenses.models.shared.accountmappinginfo import AccountMappingInfo +from codat_sync_for_expenses.models.shared.accountprototype import AccountPrototype +from codat_sync_for_expenses.models.account_reference import AccountReference +from codat_sync_for_expenses.models.account_reference1 import AccountReference1 +from codat_sync_for_expenses.models.shared.accountstatus import AccountStatus +from codat_sync_for_expenses.models.shared.accounttype import AccountType +from codat_sync_for_expenses.models.accounting_address import AccountingAddress +from codat_sync_for_expenses.models.shared.accountingaddresstype import AccountingAddressType +from codat_sync_for_expenses.models.shared.adjustmenttransactionline import AdjustmentTransactionLine +from codat_sync_for_expenses.models.shared.adjustmenttransactionrequest import AdjustmentTransactionRequest +from codat_sync_for_expenses.models.shared.adjustmenttransactionresponse import AdjustmentTransactionResponse +from codat_sync_for_expenses.models.shared.apaccountref import ApAccountRef +from codat_sync_for_expenses.models.shared.attachment import Attachment +from codat_sync_for_expenses.models.shared.bankaccount import BankAccount +from codat_sync_for_expenses.models.shared.bankaccountdetails import BankAccountDetails +from codat_sync_for_expenses.models.bank_account_prototype import BankAccountPrototype +from codat_sync_for_expenses.models.bank_account_reference import BankAccountReference +from codat_sync_for_expenses.models.shared.bankaccountstatus import BankAccountStatus +from codat_sync_for_expenses.models.shared.clientratelimitwebhook import ClientRateLimitWebhook +from codat_sync_for_expenses.models.shared.clientratelimitwebhookpayload import ClientRateLimitWebhookPayload +from codat_sync_for_expenses.models.shared.companies import Companies +from codat_sync_for_expenses.models.shared.company import Company +from codat_sync_for_expenses.models.shared.companyconfiguration import CompanyConfiguration +from codat_sync_for_expenses.models.company_details import CompanyDetails +from codat_sync_for_expenses.models.company_information import CompanyInformation +from codat_sync_for_expenses.models.shared.companyreference import CompanyReference +from codat_sync_for_expenses.models.company_reference_links import CompanyReferenceLinks +from codat_sync_for_expenses.models.shared.companyrequestbody import CompanyRequestBody +from codat_sync_for_expenses.models.shared.companysyncstatus import CompanySyncStatus +from codat_sync_for_expenses.models.shared.companyupdaterequest import CompanyUpdateRequest +from codat_sync_for_expenses.models.shared.connection import Connection +from codat_sync_for_expenses.models.shared.connections import Connections +from codat_sync_for_expenses.models.shared.contact import Contact +from codat_sync_for_expenses.models.shared.createaccountresponse import CreateAccountResponse +from codat_sync_for_expenses.models.create_account_response_all_of_data import CreateAccountResponseAllOfData +from codat_sync_for_expenses.models.create_bank_account_response import CreateBankAccountResponse +from codat_sync_for_expenses.models.create_bank_account_response_all_of_data import CreateBankAccountResponseAllOfData +from codat_sync_for_expenses.models.create_connection_request import CreateConnectionRequest +from codat_sync_for_expenses.models.shared.createcustomerresponse import CreateCustomerResponse +from codat_sync_for_expenses.models.create_customer_response_all_of_data import CreateCustomerResponseAllOfData +from codat_sync_for_expenses.models.shared.createexpenseresponse import CreateExpenseResponse +from codat_sync_for_expenses.models.shared.createreimbursableexpenseresponse import CreateReimbursableExpenseResponse +from codat_sync_for_expenses.models.shared.createsupplierresponse import CreateSupplierResponse +from codat_sync_for_expenses.models.create_supplier_response_all_of_data import CreateSupplierResponseAllOfData +from codat_sync_for_expenses.models.shared.customer import Customer +from codat_sync_for_expenses.models.shared.customerdetails import CustomerDetails +from codat_sync_for_expenses.models.shared.customerstatus import CustomerStatus +from codat_sync_for_expenses.models.shared.customers import Customers +from codat_sync_for_expenses.models.shared.dataconnectionerror import DataConnectionError +from codat_sync_for_expenses.models.shared.dataconnectionstatus import DataConnectionStatus +from codat_sync_for_expenses.models.shared.datastatus import DataStatus +from codat_sync_for_expenses.models.data_statuses import DataStatuses +from codat_sync_for_expenses.models.shared.datatype import DataType +from codat_sync_for_expenses.models.error_message import ErrorMessage +from codat_sync_for_expenses.models.shared.errorvalidation import ErrorValidation +from codat_sync_for_expenses.models.shared.errorvalidationitem import ErrorValidationItem +from codat_sync_for_expenses.models.expense_contact_ref import ExpenseContactRef +from codat_sync_for_expenses.models.shared.expensetransaction import ExpenseTransaction +from codat_sync_for_expenses.models.shared.expensetransactionline import ExpenseTransactionLine +from codat_sync_for_expenses.models.shared.expensessyncwebhook import ExpensesSyncWebhook +from codat_sync_for_expenses.models.shared.expensessyncwebhookpayload import ExpensesSyncWebhookPayload +from codat_sync_for_expenses.models.shared.halref import HalRef +from codat_sync_for_expenses.models.shared.integrationtype import IntegrationType +from codat_sync_for_expenses.models.shared.invoiceto import InvoiceTo +from codat_sync_for_expenses.models.shared.itemref import ItemRef +from codat_sync_for_expenses.models.shared.items import Items +from codat_sync_for_expenses.models.shared.links import Links +from codat_sync_for_expenses.models.shared.mappingoptions import MappingOptions +from codat_sync_for_expenses.models.shared.metadata import Metadata +from codat_sync_for_expenses.models.model3 import Model3 +from codat_sync_for_expenses.models.paging_info import PagingInfo +from codat_sync_for_expenses.models.shared.phonenumber_items import PhoneNumberItems +from codat_sync_for_expenses.models.shared.pulloperation import PullOperation +from codat_sync_for_expenses.models.shared.pulloperations import PullOperations +from codat_sync_for_expenses.models.shared.pushchangetype import PushChangeType +from codat_sync_for_expenses.models.shared.pushfieldvalidation import PushFieldValidation +from codat_sync_for_expenses.models.shared.pushoperation import PushOperation +from codat_sync_for_expenses.models.shared.pushoperationchange import PushOperationChange +from codat_sync_for_expenses.models.shared.pushoperationref import PushOperationRef +from codat_sync_for_expenses.models.shared.pushoperationstatus import PushOperationStatus +from codat_sync_for_expenses.models.shared.pushoperations import PushOperations +from codat_sync_for_expenses.models.shared.pushoption import PushOption +from codat_sync_for_expenses.models.shared.pushoptionchoice import PushOptionChoice +from codat_sync_for_expenses.models.shared.pushoptionproperty import PushOptionProperty +from codat_sync_for_expenses.models.shared.pushoptiontype import PushOptionType +from codat_sync_for_expenses.models.shared.pushvalidationinfo import PushValidationInfo +from codat_sync_for_expenses.models.shared.recordref import RecordRef +from codat_sync_for_expenses.models.shared.reimbursableexpensetransaction import ReimbursableExpenseTransaction +from codat_sync_for_expenses.models.shared.reimbursableexpensetransactionline import ReimbursableExpenseTransactionLine +from codat_sync_for_expenses.models.shared.reimbursementcontactref import ReimbursementContactRef +from codat_sync_for_expenses.models.shared.schema_transaction import SchemaTransaction +from codat_sync_for_expenses.models.shared.status import Status +from codat_sync_for_expenses.models.shared.supplementaldata import SupplementalData +from codat_sync_for_expenses.models.shared.supplier import Supplier +from codat_sync_for_expenses.models.shared.supplierdetails import SupplierDetails +from codat_sync_for_expenses.models.shared.supplierstatus import SupplierStatus +from codat_sync_for_expenses.models.shared.suppliers import Suppliers +from codat_sync_for_expenses.models.sync_complete_webhook import SyncCompleteWebhook +from codat_sync_for_expenses.models.sync_complete_webhook_data import SyncCompleteWebhookData +from codat_sync_for_expenses.models.sync_failed_webhook import SyncFailedWebhook +from codat_sync_for_expenses.models.sync_failed_webhook_data import SyncFailedWebhookData +from codat_sync_for_expenses.models.sync_initiated import SyncInitiated +from codat_sync_for_expenses.models.shared.taxratemappinginfo import TaxRateMappingInfo +from codat_sync_for_expenses.models.shared.trackingcategorymappinginfo import TrackingCategoryMappingInfo +from codat_sync_for_expenses.models.shared.trackingref import TrackingRef +from codat_sync_for_expenses.models.shared.trackingrefadjustmenttransaction import TrackingRefAdjustmentTransaction +from codat_sync_for_expenses.models.transaction import Transaction +from codat_sync_for_expenses.models.shared.transactionstatus import TransactionStatus +from codat_sync_for_expenses.models.shared.transactions import Transactions +from codat_sync_for_expenses.models.shared.transfertransactionrequest import TransferTransactionRequest +from codat_sync_for_expenses.models.transfer_transaction_request_from import TransferTransactionRequestFrom +from codat_sync_for_expenses.models.transfer_transaction_request_to import TransferTransactionRequestTo +from codat_sync_for_expenses.models.shared.transfertransactionresponse import TransferTransactionResponse +from codat_sync_for_expenses.models.update_connection import UpdateConnection +from codat_sync_for_expenses.models.shared.updatecustomerresponse import UpdateCustomerResponse +from codat_sync_for_expenses.models.update_customer_response_all_of_data import UpdateCustomerResponseAllOfData +from codat_sync_for_expenses.models.shared.updateexpenserequest import UpdateExpenseRequest +from codat_sync_for_expenses.models.shared.updateexpenseresponse import UpdateExpenseResponse +from codat_sync_for_expenses.models.shared.updatereimbursableexpensetransactionrequest import UpdateReimbursableExpenseTransactionRequest +from codat_sync_for_expenses.models.shared.updatesupplierresponse import UpdateSupplierResponse +from codat_sync_for_expenses.models.update_supplier_response_all_of_data import UpdateSupplierResponseAllOfData +from codat_sync_for_expenses.models.valid_data_type_links import ValidDataTypeLinks +from codat_sync_for_expenses.models.shared.validation import Validation +from codat_sync_for_expenses.models.shared.validationitem import ValidationItem +from codat_sync_for_expenses.models.weblink import Weblink diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/_compat/__init__.py b/sync-for-expenses/src/codat_sync_for_expenses/models/_compat/__init__.py new file mode 100644 index 000000000..70271e525 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/_compat/__init__.py @@ -0,0 +1,3 @@ +"""Leaf modules holding Speakeasy-name compat enums. Nothing here imports from the +package, so a flat model can import these without triggering models/shared/__init__ +(which re-exports flat models and would form an import cycle).""" diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/_compat/companyinformation.py b/sync-for-expenses/src/codat_sync_for_expenses/models/_compat/companyinformation.py new file mode 100644 index 000000000..a5b25a3f6 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/_compat/companyinformation.py @@ -0,0 +1,10 @@ +from __future__ import annotations + +from enum import Enum + + +class CompanyInformationSchemasType(str, Enum): + """Speakeasy-name compat for CompanyInformationType (matched by value set).""" + WEBSITE = 'Website' + SOCIAL = 'Social' + UNKNOWN = 'Unknown' diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/_compat/expensecontactref.py b/sync-for-expenses/src/codat_sync_for_expenses/models/_compat/expensecontactref.py new file mode 100644 index 000000000..d2ee18a2d --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/_compat/expensecontactref.py @@ -0,0 +1,8 @@ +from __future__ import annotations + +from enum import Enum + + +class ExpenseContactRefType(str, Enum): + """Speakeasy-name compat for Type (matched by value set).""" + SUPPLIER = 'Supplier' diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/_compat/schema_datatype.py b/sync-for-expenses/src/codat_sync_for_expenses/models/_compat/schema_datatype.py new file mode 100644 index 000000000..1d7d3b5ca --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/_compat/schema_datatype.py @@ -0,0 +1,50 @@ +from __future__ import annotations + +from enum import Enum + + +class SchemaDataType(str, Enum): + """Speakeasy-name compat for DataTypes (matched by value set).""" + 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-expenses/src/codat_sync_for_expenses/models/_compat/transaction.py b/sync-for-expenses/src/codat_sync_for_expenses/models/_compat/transaction.py new file mode 100644 index 000000000..7d03a501f --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/_compat/transaction.py @@ -0,0 +1,12 @@ +from __future__ import annotations + +from enum import Enum + + +class TransactionDefinitionsStatus(str, Enum): + """Speakeasy-name compat for ExpensesSyncWebhookStatus (matched by value set).""" + UNKNOWN = 'Unknown' + PUSH_ERROR = 'PushError' + COMPLETED = 'Completed' + FAILED = 'Failed' + PENDING = 'Pending' diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/account.py b/sync-for-expenses/src/codat_sync_for_expenses/models/account.py new file mode 100644 index 000000000..b4b078185 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/account.py @@ -0,0 +1,164 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.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_expenses.models.shared.accountstatus import AccountStatus +from codat_sync_for_expenses.models.shared.accounttype import AccountType +from codat_sync_for_expenses.models.shared.metadata import Metadata, MetadataTypedDict +from codat_sync_for_expenses.models.shared.supplementaldata import SupplementalData, SupplementalDataTypedDict +from codat_sync_for_expenses.models.valid_data_type_links import ValidDataTypeLinks, ValidDataTypeLinksTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class Account(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} + """ + > **Language tip:** Accounts are also referred to as **chart of accounts**, **nominal accounts**, and **general ledger**. ## Overview Accounts are the categories a business uses to record accounting transactions. From the Accounts endpoints, you can retrieve a list of all accounts for a specified company. The categories for an account include: * Asset * Expense * Income * Liability * Equity. The same account may have a different category based on the integration it is used in. For example, a current account (known as checking in the US) should be categorized as `Asset.Current` for Xero, and `Asset.Bank.Checking` for QuickBooks Online. At the same time, each integration may have its own requirements to the categories. For example, a Paypal account in Xero is of the `Asset.Bank` category and therefore requires additional properties to be provided. To determine the list of allowed categories for a specific integration, you can: - Follow our [Create, update, delete data](https://docs.codat.io/using-the-api/push) guide and use the [Get create account model](https://docs.codat.io/sync-for-expenses-api#/operations/get-create-chartOfAccounts-model). - Refer to the integration's own documentation. > **Accounts with no category** > > If an account is pulled from the chart of accounts and its nominal code does not lie within the category layout for the company's accounts, then the **type** is `Unknown`. The **fullyQualifiedCategory** and **fullyQualifiedName** fields return `null`. > > This approach gives a true representation of the company's accounts whilst preventing distorting financials such as a company's profit and loss and balance sheet reports. + """ # noqa: E501 + nominal_code: Optional[str] = Field(default=None, 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: Optional[str] = Field(default=None, description="Name of the account.") + description: Optional[str] = Field(default=None, description="Description for the account.") + fully_qualified_category: Optional[str] = Field(default=None, description="Full category of the account. For example, `Liability.Current` or `Income.Revenue`. To determine a list of possible categories for each integration, see our examples, follow our [Create, update, delete data](https://docs.codat.io/using-the-api/push) guide, or refer to the integration's own documentation.", alias="fullyQualifiedCategory") + fully_qualified_name: Optional[str] = Field(default=None, description="Full name of the account, for example: - `Cash On Hand` - `Rents Held In Trust` - `Fixed Asset`", alias="fullyQualifiedName") + 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.") + current_balance: Annotated[Optional[Decimal], BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(default=None, description="Current balance in the account.", alias="currentBalance") + type: Optional[AccountType] = None + status: Optional[AccountStatus] = None + is_bank_account: Optional[bool] = Field(default=None, description="Confirms whether the account is a bank account or not.", alias="isBankAccount") + valid_datatype_links: Optional[List[ValidDataTypeLinks]] = Field(default=None, description="The validDatatypeLinks can be used to determine whether an account can be correctly mapped to another object; for example, accounts with a `type` of `income` might only support being used on an Invoice and Direct Income. For more information, see [Valid Data Type Links](/sync-for-expenses-api#/schemas/ValidDataTypeLinks).", alias="validDatatypeLinks") + supplemental_data: Optional[SupplementalData] = Field(default=None, alias="supplementalData") + id: Optional[str] = Field(default=None, description="Identifier for the account, unique for the company.") + metadata: Optional[Metadata] = None + modified_date: Optional[str] = Field(default=None, description="The date when the record was last fetched from the accounting software, commerce software, or open banking provider and updated in Codat’s data cache. Use it to identify and retrieve records that have changed since your last fetch. For example, filtering `modifiedDate` to today will provide new records updated in Codat today. This date is populated for all data types except for attachments, balance sheets, company information, and profit & loss reports ([read more](https://docs.codat.io/using-the-api/modified-dates#modified-date)). In Codat's data model, dates and times are represented using the ISO 8601 standard.", alias="modifiedDate") + 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]] = ["nominalCode", "name", "description", "fullyQualifiedCategory", "fullyQualifiedName", "currency", "currentBalance", "type", "status", "isBankAccount", "validDatatypeLinks", "supplementalData", "id", "metadata", "modifiedDate", "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 Account 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 valid_datatype_links (list) + _items = [] + if self.valid_datatype_links: + for _item_valid_datatype_links in self.valid_datatype_links: + if _item_valid_datatype_links: + _items.append(_item_valid_datatype_links.to_dict()) + _dict['validDatatypeLinks'] = _items + # override the default output from pydantic by calling `to_dict()` of supplemental_data + if self.supplemental_data: + _dict['supplementalData'] = self.supplemental_data.to_dict() + # override the default output from pydantic by calling `to_dict()` of metadata + if self.metadata: + _dict['metadata'] = self.metadata.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Account from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "nominalCode": obj.get("nominalCode"), + "name": obj.get("name"), + "description": obj.get("description"), + "fullyQualifiedCategory": obj.get("fullyQualifiedCategory"), + "fullyQualifiedName": obj.get("fullyQualifiedName"), + "currency": obj.get("currency"), + "currentBalance": obj.get("currentBalance"), + "type": obj.get("type"), + "status": obj.get("status"), + "isBankAccount": obj.get("isBankAccount"), + "validDatatypeLinks": [ValidDataTypeLinks.from_dict(_item) for _item in obj["validDatatypeLinks"]] if obj.get("validDatatypeLinks") is not None else None, + "supplementalData": SupplementalData.from_dict(obj["supplementalData"]) if obj.get("supplementalData") is not None else None, + "id": obj.get("id"), + "metadata": Metadata.from_dict(obj["metadata"]) if obj.get("metadata") is not None else None, + "modifiedDate": obj.get("modifiedDate"), + "sourceModifiedDate": obj.get("sourceModifiedDate") + }) + return _obj + + + + + +class AccountTypedDict(TypedDict): + """TypedDict variant of Account, for dict-literal request/response inputs.""" + nominal_code: NotRequired[Optional[str]] + name: NotRequired[Optional[str]] + description: NotRequired[Optional[str]] + fully_qualified_category: NotRequired[Optional[str]] + fully_qualified_name: NotRequired[Optional[str]] + currency: NotRequired[Optional[str]] + current_balance: NotRequired[Optional[Decimal]] + type: NotRequired[Optional[AccountType]] + status: NotRequired[Optional[AccountStatus]] + is_bank_account: NotRequired[Optional[bool]] + valid_datatype_links: NotRequired[Optional[List[ValidDataTypeLinksTypedDict]]] + supplemental_data: NotRequired[Optional[SupplementalDataTypedDict]] + id: NotRequired[Optional[str]] + metadata: NotRequired[Optional[MetadataTypedDict]] + modified_date: NotRequired[Optional[str]] + source_modified_date: NotRequired[Optional[str]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/account_mapping_info_account_type.py b/sync-for-expenses/src/codat_sync_for_expenses/models/account_mapping_info_account_type.py new file mode 100644 index 000000000..1b0a64bad --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/account_mapping_info_account_type.py @@ -0,0 +1,12 @@ +from __future__ import annotations + +from enum import Enum + + +class AccountMappingInfoAccountType(str, Enum): + """AccountMappingInfoAccountType enum (lifted from inline OAS enum).""" + ASSET = 'Asset' + LIABILITY = 'Liability' + INCOME = 'Income' + EXPENSE = 'Expense' + EQUITY = 'Equity' diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/account_reference.py b/sync-for-expenses/src/codat_sync_for_expenses/models/account_reference.py new file mode 100644 index 000000000..900d74192 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/account_reference.py @@ -0,0 +1,99 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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 import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class AccountReference(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} + """ + Reference of the account you are transferring money from. + """ # noqa: E501 + id: str = Field(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 AccountReference 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 AccountReference 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 AccountReferenceTypedDict(TypedDict): + """TypedDict variant of AccountReference, for dict-literal request/response inputs.""" + id: NotRequired[str] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/account_reference1.py b/sync-for-expenses/src/codat_sync_for_expenses/models/account_reference1.py new file mode 100644 index 000000000..87d687063 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/account_reference1.py @@ -0,0 +1,99 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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 import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class AccountReference1(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} + """ + Reference of the account you are transferring money to. + """ # noqa: E501 + id: str = Field(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 AccountReference1 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 AccountReference1 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 AccountReference1TypedDict(TypedDict): + """TypedDict variant of AccountReference1, for dict-literal request/response inputs.""" + id: NotRequired[str] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/accounting_address.py b/sync-for-expenses/src/codat_sync_for_expenses/models/accounting_address.py new file mode 100644 index 000000000..61d616800 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/accounting_address.py @@ -0,0 +1,123 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.models.shared.accountingaddresstype import AccountingAddressType +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL +class AccountingAddress(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) + } + """ + AccountingAddress + """ # noqa: E501 + type: AccountingAddressType + 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 customer address.") + 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 AccountingAddress 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 AccountingAddress 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"), + "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 + + + + + +class AccountingAddressTypedDict(TypedDict): + """TypedDict variant of AccountingAddress, for dict-literal request/response inputs.""" + type: AccountingAddressType + 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-expenses/src/codat_sync_for_expenses/models/bank_account_prototype.py b/sync-for-expenses/src/codat_sync_for_expenses/models/bank_account_prototype.py new file mode 100644 index 000000000..d0e2653e6 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/bank_account_prototype.py @@ -0,0 +1,146 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.utils.serializers import serialize_decimal, validate_decimal +from codat_sync_for_expenses.models.bank_account_type import BankAccountType +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 codat_sync_for_expenses.models.shared.bankaccountstatus import BankAccountStatus +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class BankAccountPrototype(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} + """ + BankAccountPrototype + """ # noqa: E501 + account_name: Optional[str] = Field(default=None, description="Name of the bank account in the accounting software.", alias="accountName") + account_type: Optional[BankAccountType] = Field(default=None, description="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.", alias="accountType") + nominal_code: Optional[str] = Field(default=None, description="Code used to identify each nominal account for a business.", alias="nominalCode") + sort_code: Optional[str] = Field(default=None, 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") + account_number: Optional[str] = Field(default=None, 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. FreeAgent integrations For Credit accounts, only the last four digits are required. For other types, the field is optional.", alias="accountNumber") + i_ban: Optional[str] = Field(default=None, description="International bank account number of the account. Often used when making or receiving international payments.", alias="iBan") + 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.") + balance: Annotated[Optional[Decimal], BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(default=None, description="Balance of the bank account.") + institution: Optional[str] = Field(default=None, description="The institution of the bank account.") + available_balance: Annotated[Optional[Decimal], BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(default=None, description="Total available balance of the bank account as reported by the underlying data source. This may take into account overdrafts or pending transactions for example.", alias="availableBalance") + overdraft_limit: Annotated[Optional[Decimal], BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(default=None, description="Pre-arranged overdraft limit of the account. The value is always positive. For example, an overdraftLimit of `1000` means that the balance of the account can go down to `-1000`.", alias="overdraftLimit") + status: Optional[BankAccountStatus] = None + __properties: ClassVar[List[str]] = ["accountName", "accountType", "nominalCode", "sortCode", "accountNumber", "iBan", "currency", "balance", "institution", "availableBalance", "overdraftLimit", "status"] + + @field_validator('account_type') + def account_type_validate_enum(cls, value): + """Validates the enum""" + if value is None: + return value + + if value not in set(['Unknown', 'Credit', 'Debit']): + raise ValueError("must be one of enum values ('Unknown', 'Credit', 'Debit')") + 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 BankAccountPrototype 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 BankAccountPrototype from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "accountName": obj.get("accountName"), + "accountType": obj.get("accountType"), + "nominalCode": obj.get("nominalCode"), + "sortCode": obj.get("sortCode"), + "accountNumber": obj.get("accountNumber"), + "iBan": obj.get("iBan"), + "currency": obj.get("currency"), + "balance": obj.get("balance"), + "institution": obj.get("institution"), + "availableBalance": obj.get("availableBalance"), + "overdraftLimit": obj.get("overdraftLimit"), + "status": obj.get("status") + }) + return _obj + + + + + +class BankAccountPrototypeTypedDict(TypedDict): + """TypedDict variant of BankAccountPrototype, for dict-literal request/response inputs.""" + account_name: NotRequired[Optional[str]] + account_type: NotRequired[Optional[BankAccountType]] + nominal_code: NotRequired[Optional[str]] + sort_code: NotRequired[Optional[str]] + account_number: NotRequired[Optional[str]] + i_ban: NotRequired[Optional[str]] + currency: NotRequired[Optional[str]] + balance: NotRequired[Optional[Decimal]] + institution: NotRequired[Optional[str]] + available_balance: NotRequired[Optional[Decimal]] + overdraft_limit: NotRequired[Optional[Decimal]] + status: NotRequired[Optional[BankAccountStatus]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/bank_account_reference.py b/sync-for-expenses/src/codat_sync_for_expenses/models/bank_account_reference.py new file mode 100644 index 000000000..da7cb338d --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/bank_account_reference.py @@ -0,0 +1,99 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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 BankAccountReference(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} + """ + BankAccountReference + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Identifier of the bank account.") + __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 BankAccountReference 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 BankAccountReference 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 BankAccountReferenceTypedDict(TypedDict): + """TypedDict variant of BankAccountReference, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/bank_account_type.py b/sync-for-expenses/src/codat_sync_for_expenses/models/bank_account_type.py new file mode 100644 index 000000000..7626a6785 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/bank_account_type.py @@ -0,0 +1,10 @@ +from __future__ import annotations + +from enum import Enum + + +class BankAccountType(str, Enum): + """BankAccountType enum (lifted from inline OAS enum).""" + UNKNOWN = 'Unknown' + CREDIT = 'Credit' + DEBIT = 'Debit' diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/company_details.py b/sync-for-expenses/src/codat_sync_for_expenses/models/company_details.py new file mode 100644 index 000000000..ef86d165f --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/company_details.py @@ -0,0 +1,141 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.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="A description of the property.") + 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="Date of the transfer transaction as recorded in the accounting software.", alias="lastSync") + created: Optional[str] = Field(default=None, description="Date of the transfer transaction as recorded in the accounting software.") + 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-expenses/src/codat_sync_for_expenses/models/company_information.py b/sync-for-expenses/src/codat_sync_for_expenses/models/company_information.py new file mode 100644 index 000000000..7aa26797f --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/company_information.py @@ -0,0 +1,171 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.models.accounting_address import AccountingAddress, AccountingAddressTypedDict +from codat_sync_for_expenses.models.shared.phonenumber_items import PhoneNumberItems, PhoneNumberItemsTypedDict +from codat_sync_for_expenses.models.shared.supplementaldata import SupplementalData, SupplementalDataTypedDict +from codat_sync_for_expenses.models.weblink import Weblink, WeblinkTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL +class CompanyInformation(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'accountingPlatformRef', 'accounting_platform_ref', 'addresses', 'baseCurrency', 'base_currency', 'companyLegalName', 'companyName', 'company_legal_name', 'company_name', 'phoneNumbers', 'phone_numbers', 'registrationNumber', 'registration_number', 'sourceUrls', 'source_urls', 'taxNumber', 'tax_number', 'webLinks', 'web_links'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + Company info provides standard details about a linked company such as their address, phone number, and company registration. > **Company information or companies?** > > Company information is standard information that is held in the accounting software about a company. `Companies` is an endpoint that lists businesses in the Codat system that have linked and shared their data sources. + """ # noqa: E501 + company_name: OptionalNullable[str] = Field(default=UNSET, description="Name of the linked company.", alias="companyName") + accounting_platform_ref: OptionalNullable[str] = Field(default=UNSET, description="Identifier or reference for the company in the accounting software.", alias="accountingPlatformRef") + company_legal_name: OptionalNullable[str] = Field(default=UNSET, description="Registered legal name of the linked company.", alias="companyLegalName") + addresses: OptionalNullable[List[AccountingAddress]] = Field(default=UNSET, description="An array of Addresses.") + phone_numbers: OptionalNullable[List[PhoneNumberItems]] = Field(default=UNSET, description="An array of phone numbers.", alias="phoneNumbers") + web_links: OptionalNullable[List[Weblink]] = Field(default=UNSET, description="An array of weblinks.", alias="webLinks") + ledger_lock_date: Optional[str] = Field(default=None, description="If set in the accounting software, the date (in the ISO 8601 date/time format) after which accounting transactions cannot be edited. Commonly used when books are closed at year-end.", alias="ledgerLockDate") + registration_number: OptionalNullable[str] = Field(default=UNSET, description="Registration number given to the linked company by the companies authority in the country of origin. In the UK this is Companies House.", alias="registrationNumber") + tax_number: OptionalNullable[str] = Field(default=UNSET, description="Company tax number.", alias="taxNumber") + financial_year_start_date: Optional[str] = Field(default=None, description="Start date of the financial year for the company.", alias="financialYearStartDate") + 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") + source_urls: OptionalNullable[Dict[str, str]] = Field(default=UNSET, description="URL addresses for the accounting source. For example, for Xero integrations two URLs are returned. These have many potential use cases, such as [deep linking](https://developer.xero.com/documentation/api-guides/deep-link-xero).", alias="sourceUrls") + created_date: Optional[str] = Field(default=None, description="Date the linked company was created in the accounting software.", alias="createdDate") + supplemental_data: Optional[SupplementalData] = Field(default=None, alias="supplementalData") + __properties: ClassVar[List[str]] = ["companyName", "accountingPlatformRef", "companyLegalName", "addresses", "phoneNumbers", "webLinks", "ledgerLockDate", "registrationNumber", "taxNumber", "financialYearStartDate", "baseCurrency", "sourceUrls", "createdDate", "supplementalData"] + + 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, + ) + # 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 + # override the default output from pydantic by calling `to_dict()` of each item in phone_numbers (list) + _items = [] + if self.phone_numbers: + for _item_phone_numbers in self.phone_numbers: + if _item_phone_numbers: + _items.append(_item_phone_numbers.to_dict()) + _dict['phoneNumbers'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in web_links (list) + _items = [] + if self.web_links: + for _item_web_links in self.web_links: + if _item_web_links: + _items.append(_item_web_links.to_dict()) + _dict['webLinks'] = _items + # override the default output from pydantic by calling `to_dict()` of supplemental_data + if self.supplemental_data: + _dict['supplementalData'] = self.supplemental_data.to_dict() + 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"), + "accountingPlatformRef": obj.get("accountingPlatformRef"), + "companyLegalName": obj.get("companyLegalName"), + "addresses": [AccountingAddress.from_dict(_item) for _item in obj["addresses"]] if obj.get("addresses") is not None else None, + "phoneNumbers": [PhoneNumberItems.from_dict(_item) for _item in obj["phoneNumbers"]] if obj.get("phoneNumbers") is not None else None, + "webLinks": [Weblink.from_dict(_item) for _item in obj["webLinks"]] if obj.get("webLinks") is not None else None, + "ledgerLockDate": obj.get("ledgerLockDate"), + "registrationNumber": obj.get("registrationNumber"), + "taxNumber": obj.get("taxNumber"), + "financialYearStartDate": obj.get("financialYearStartDate"), + "baseCurrency": obj.get("baseCurrency"), + "sourceUrls": obj.get("sourceUrls"), + "createdDate": obj.get("createdDate"), + "supplementalData": SupplementalData.from_dict(obj["supplementalData"]) if obj.get("supplementalData") is not None else None + }) + return _obj + + + + + +class CompanyInformationTypedDict(TypedDict): + """TypedDict variant of CompanyInformation, for dict-literal request/response inputs.""" + company_name: NotRequired[Optional[str]] + accounting_platform_ref: NotRequired[Optional[str]] + company_legal_name: NotRequired[Optional[str]] + addresses: NotRequired[Optional[List[AccountingAddressTypedDict]]] + phone_numbers: NotRequired[Optional[List[PhoneNumberItemsTypedDict]]] + web_links: NotRequired[Optional[List[WeblinkTypedDict]]] + ledger_lock_date: NotRequired[Optional[str]] + registration_number: NotRequired[Optional[str]] + tax_number: NotRequired[Optional[str]] + financial_year_start_date: NotRequired[Optional[str]] + base_currency: NotRequired[Optional[str]] + source_urls: NotRequired[Optional[Dict[str, str]]] + created_date: NotRequired[Optional[str]] + supplemental_data: NotRequired[Optional[SupplementalDataTypedDict]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/company_information_type.py b/sync-for-expenses/src/codat_sync_for_expenses/models/company_information_type.py new file mode 100644 index 000000000..8e86c6fd8 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/company_information_type.py @@ -0,0 +1,10 @@ +from __future__ import annotations + +from enum import Enum + + +class CompanyInformationType(str, Enum): + """CompanyInformationType enum (lifted from inline OAS enum).""" + WEBSITE = 'Website' + SOCIAL = 'Social' + UNKNOWN = 'Unknown' diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/company_reference_links.py b/sync-for-expenses/src/codat_sync_for_expenses/models/company_reference_links.py new file mode 100644 index 000000000..27ca8f3d6 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/company_reference_links.py @@ -0,0 +1,99 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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-expenses/src/codat_sync_for_expenses/models/create_account_response_all_of_data.py b/sync-for-expenses/src/codat_sync_for_expenses/models/create_account_response_all_of_data.py new file mode 100644 index 000000000..7d49d3dfb --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/create_account_response_all_of_data.py @@ -0,0 +1,164 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.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_expenses.models.shared.accountstatus import AccountStatus +from codat_sync_for_expenses.models.shared.accounttype import AccountType +from codat_sync_for_expenses.models.shared.metadata import Metadata, MetadataTypedDict +from codat_sync_for_expenses.models.shared.supplementaldata import SupplementalData, SupplementalDataTypedDict +from codat_sync_for_expenses.models.valid_data_type_links import ValidDataTypeLinks, ValidDataTypeLinksTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class CreateAccountResponseAllOfData(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} + """ + CreateAccountResponseAllOfData + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Identifier for the account, unique for the company.") + nominal_code: Optional[str] = Field(default=None, 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: Optional[str] = Field(default=None, description="Name of the account.") + description: Optional[str] = Field(default=None, description="Description for the account.") + fully_qualified_category: Optional[str] = Field(default=None, description="Full category of the account. For example, `Liability.Current` or `Income.Revenue`. To determine a list of possible categories for each integration, see our examples, follow our [Create, update, delete data](https://docs.codat.io/using-the-api/push) guide, or refer to the integration's own documentation.", alias="fullyQualifiedCategory") + fully_qualified_name: Optional[str] = Field(default=None, description="Full name of the account, for example: - `Cash On Hand` - `Rents Held In Trust` - `Fixed Asset`", alias="fullyQualifiedName") + 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.") + current_balance: Annotated[Optional[Decimal], BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(default=None, description="Current balance in the account.", alias="currentBalance") + type: Optional[AccountType] = None + status: Optional[AccountStatus] = None + is_bank_account: Optional[bool] = Field(default=None, description="Confirms whether the account is a bank account or not.", alias="isBankAccount") + valid_datatype_links: Optional[List[ValidDataTypeLinks]] = Field(default=None, description="The validDatatypeLinks can be used to determine whether an account can be correctly mapped to another object; for example, accounts with a `type` of `income` might only support being used on an Invoice and Direct Income. For more information, see [Valid Data Type Links](/sync-for-expenses-api#/schemas/ValidDataTypeLinks).", alias="validDatatypeLinks") + supplemental_data: Optional[SupplementalData] = Field(default=None, alias="supplementalData") + metadata: Optional[Metadata] = None + modified_date: Optional[str] = Field(default=None, description="The date when the record was last fetched from the accounting software, commerce software, or open banking provider and updated in Codat’s data cache. Use it to identify and retrieve records that have changed since your last fetch. For example, filtering `modifiedDate` to today will provide new records updated in Codat today. This date is populated for all data types except for attachments, balance sheets, company information, and profit & loss reports ([read more](https://docs.codat.io/using-the-api/modified-dates#modified-date)). In Codat's data model, dates and times are represented using the ISO 8601 standard.", alias="modifiedDate") + 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", "nominalCode", "name", "description", "fullyQualifiedCategory", "fullyQualifiedName", "currency", "currentBalance", "type", "status", "isBankAccount", "validDatatypeLinks", "supplementalData", "metadata", "modifiedDate", "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 CreateAccountResponseAllOfData 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 valid_datatype_links (list) + _items = [] + if self.valid_datatype_links: + for _item_valid_datatype_links in self.valid_datatype_links: + if _item_valid_datatype_links: + _items.append(_item_valid_datatype_links.to_dict()) + _dict['validDatatypeLinks'] = _items + # override the default output from pydantic by calling `to_dict()` of supplemental_data + if self.supplemental_data: + _dict['supplementalData'] = self.supplemental_data.to_dict() + # override the default output from pydantic by calling `to_dict()` of metadata + if self.metadata: + _dict['metadata'] = self.metadata.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CreateAccountResponseAllOfData 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"), + "nominalCode": obj.get("nominalCode"), + "name": obj.get("name"), + "description": obj.get("description"), + "fullyQualifiedCategory": obj.get("fullyQualifiedCategory"), + "fullyQualifiedName": obj.get("fullyQualifiedName"), + "currency": obj.get("currency"), + "currentBalance": obj.get("currentBalance"), + "type": obj.get("type"), + "status": obj.get("status"), + "isBankAccount": obj.get("isBankAccount"), + "validDatatypeLinks": [ValidDataTypeLinks.from_dict(_item) for _item in obj["validDatatypeLinks"]] if obj.get("validDatatypeLinks") is not None else None, + "supplementalData": SupplementalData.from_dict(obj["supplementalData"]) if obj.get("supplementalData") is not None else None, + "metadata": Metadata.from_dict(obj["metadata"]) if obj.get("metadata") is not None else None, + "modifiedDate": obj.get("modifiedDate"), + "sourceModifiedDate": obj.get("sourceModifiedDate") + }) + return _obj + + + + + +class CreateAccountResponseAllOfDataTypedDict(TypedDict): + """TypedDict variant of CreateAccountResponseAllOfData, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + nominal_code: NotRequired[Optional[str]] + name: NotRequired[Optional[str]] + description: NotRequired[Optional[str]] + fully_qualified_category: NotRequired[Optional[str]] + fully_qualified_name: NotRequired[Optional[str]] + currency: NotRequired[Optional[str]] + current_balance: NotRequired[Optional[Decimal]] + type: NotRequired[Optional[AccountType]] + status: NotRequired[Optional[AccountStatus]] + is_bank_account: NotRequired[Optional[bool]] + valid_datatype_links: NotRequired[Optional[List[ValidDataTypeLinksTypedDict]]] + supplemental_data: NotRequired[Optional[SupplementalDataTypedDict]] + metadata: NotRequired[Optional[MetadataTypedDict]] + modified_date: NotRequired[Optional[str]] + source_modified_date: NotRequired[Optional[str]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/create_bank_account_response.py b/sync-for-expenses/src/codat_sync_for_expenses/models/create_bank_account_response.py new file mode 100644 index 000000000..12710f708 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/create_bank_account_response.py @@ -0,0 +1,171 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.models.shared.datatype 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_expenses.models.create_bank_account_response_all_of_data import CreateBankAccountResponseAllOfData +from codat_sync_for_expenses.models.shared.pushoperationchange import PushOperationChange, PushOperationChangeTypedDict +from codat_sync_for_expenses.models.shared.pushoperationstatus import PushOperationStatus +from codat_sync_for_expenses.models.shared.validation import Validation, ValidationTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL +class CreateBankAccountResponse(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'changes', 'data', 'errorMessage', 'error_message', 'timeoutInMinutes', 'timeoutInSeconds', 'timeout_in_minutes', 'timeout_in_seconds'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + CreateBankAccountResponse + """ # noqa: E501 + changes: OptionalNullable[List[PushOperationChange]] = Field(default=UNSET, description="Contains a single entry that communicates which record has changed and the manner in which it changed. ") + data_type: Optional[DataType] = 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="The datetime when the push was requested.", alias="requestedOnUtc") + completed_on_utc: Optional[str] = Field(default=None, description="The datetime when the push was completed, null if Pending.", alias="completedOnUtc") + timeout_in_minutes: OptionalNullable[int] = Field(default=UNSET, description="Number of minutes the push operation must complete within before it times out.", alias="timeoutInMinutes") + timeout_in_seconds: OptionalNullable[int] = Field(default=UNSET, description="Number of seconds the push operation must complete within before it times out.", alias="timeoutInSeconds") + status: PushOperationStatus + error_message: OptionalNullable[str] = Field(default=UNSET, description="A message about the error.", alias="errorMessage") + validation: Optional[Validation] = None + status_code: int = Field(description="Push status code.", alias="statusCode") + data: OptionalNullable[CreateBankAccountResponseAllOfData] = UNSET + __properties: ClassVar[List[str]] = ["changes", "dataType", "companyId", "pushOperationKey", "dataConnectionKey", "requestedOnUtc", "completedOnUtc", "timeoutInMinutes", "timeoutInSeconds", "status", "errorMessage", "validation", "statusCode", "data"] + + @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 CreateBankAccountResponse 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() + # override the default output from pydantic by calling `to_dict()` of data + if self.data: + _dict['data'] = self.data.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CreateBankAccountResponse 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"), + "data": CreateBankAccountResponseAllOfData.from_dict(obj["data"]) if obj.get("data") is not None else None + }) + return _obj + + + + + +class CreateBankAccountResponseTypedDict(TypedDict): + """TypedDict variant of CreateBankAccountResponse, for dict-literal request/response inputs.""" + changes: NotRequired[Optional[List[PushOperationChangeTypedDict]]] + data_type: NotRequired[Optional[DataType]] + 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] + data: NotRequired[Optional[CreateBankAccountResponseAllOfData]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/create_bank_account_response_all_of_data.py b/sync-for-expenses/src/codat_sync_for_expenses/models/create_bank_account_response_all_of_data.py new file mode 100644 index 000000000..ffc821c3b --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/create_bank_account_response_all_of_data.py @@ -0,0 +1,170 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.utils.serializers import serialize_decimal, validate_decimal +from codat_sync_for_expenses.models.shared.accounttype import AccountType +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 codat_sync_for_expenses.models.shared.bankaccountstatus import BankAccountStatus +from codat_sync_for_expenses.models.shared.metadata import Metadata, MetadataTypedDict +from codat_sync_for_expenses.models.shared.supplementaldata import SupplementalData, SupplementalDataTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_sync_for_expenses.models.bank_account_type import BankAccountType +class CreateBankAccountResponseAllOfData(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} + """ + CreateBankAccountResponseAllOfData + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Identifier for the account, unique for the company in the accounting software.") + account_name: Optional[str] = Field(default=None, description="Name of the bank account in the accounting software.", alias="accountName") + account_type: Optional[BankAccountType] = Field(default=None, description="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.", alias="accountType") + nominal_code: Optional[str] = Field(default=None, description="Code used to identify each nominal account for a business.", alias="nominalCode") + sort_code: Optional[str] = Field(default=None, 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") + account_number: Optional[str] = Field(default=None, 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. FreeAgent integrations For Credit accounts, only the last four digits are required. For other types, the field is optional.", alias="accountNumber") + i_ban: Optional[str] = Field(default=None, description="International bank account number of the account. Often used when making or receiving international payments.", alias="iBan") + 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.") + balance: Annotated[Optional[Decimal], BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(default=None, description="Balance of the bank account.") + institution: Optional[str] = Field(default=None, description="The institution of the bank account.") + available_balance: Annotated[Optional[Decimal], BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(default=None, description="Total available balance of the bank account as reported by the underlying data source. This may take into account overdrafts or pending transactions for example.", alias="availableBalance") + overdraft_limit: Annotated[Optional[Decimal], BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(default=None, description="Pre-arranged overdraft limit of the account. The value is always positive. For example, an overdraftLimit of `1000` means that the balance of the account can go down to `-1000`.", alias="overdraftLimit") + status: Optional[BankAccountStatus] = None + metadata: Optional[Metadata] = None + supplemental_data: Optional[SupplementalData] = Field(default=None, alias="supplementalData") + modified_date: Optional[str] = Field(default=None, description="The date when the record was last fetched from the accounting software, commerce software, or open banking provider and updated in Codat’s data cache. Use it to identify and retrieve records that have changed since your last fetch. For example, filtering `modifiedDate` to today will provide new records updated in Codat today. This date is populated for all data types except for attachments, balance sheets, company information, and profit & loss reports ([read more](https://docs.codat.io/using-the-api/modified-dates#modified-date)). In Codat's data model, dates and times are represented using the ISO 8601 standard.", alias="modifiedDate") + 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", "accountName", "accountType", "nominalCode", "sortCode", "accountNumber", "iBan", "currency", "balance", "institution", "availableBalance", "overdraftLimit", "status", "metadata", "supplementalData", "modifiedDate", "sourceModifiedDate"] + + @field_validator('account_type') + def account_type_validate_enum(cls, value): + """Validates the enum""" + if value is None: + return value + + if value not in set(['Unknown', 'Credit', 'Debit']): + raise ValueError("must be one of enum values ('Unknown', 'Credit', 'Debit')") + 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 CreateBankAccountResponseAllOfData 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 metadata + if self.metadata: + _dict['metadata'] = self.metadata.to_dict() + # override the default output from pydantic by calling `to_dict()` of supplemental_data + if self.supplemental_data: + _dict['supplementalData'] = self.supplemental_data.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CreateBankAccountResponseAllOfData 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"), + "accountName": obj.get("accountName"), + "accountType": obj.get("accountType"), + "nominalCode": obj.get("nominalCode"), + "sortCode": obj.get("sortCode"), + "accountNumber": obj.get("accountNumber"), + "iBan": obj.get("iBan"), + "currency": obj.get("currency"), + "balance": obj.get("balance"), + "institution": obj.get("institution"), + "availableBalance": obj.get("availableBalance"), + "overdraftLimit": obj.get("overdraftLimit"), + "status": obj.get("status"), + "metadata": Metadata.from_dict(obj["metadata"]) if obj.get("metadata") is not None else None, + "supplementalData": SupplementalData.from_dict(obj["supplementalData"]) if obj.get("supplementalData") is not None else None, + "modifiedDate": obj.get("modifiedDate"), + "sourceModifiedDate": obj.get("sourceModifiedDate") + }) + return _obj + + + + + +class CreateBankAccountResponseAllOfDataTypedDict(TypedDict): + """TypedDict variant of CreateBankAccountResponseAllOfData, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + account_name: NotRequired[Optional[str]] + account_type: NotRequired[Optional[BankAccountType]] + nominal_code: NotRequired[Optional[str]] + sort_code: NotRequired[Optional[str]] + account_number: NotRequired[Optional[str]] + i_ban: NotRequired[Optional[str]] + currency: NotRequired[Optional[str]] + balance: NotRequired[Optional[Decimal]] + institution: NotRequired[Optional[str]] + available_balance: NotRequired[Optional[Decimal]] + overdraft_limit: NotRequired[Optional[Decimal]] + status: NotRequired[Optional[BankAccountStatus]] + metadata: NotRequired[Optional[MetadataTypedDict]] + supplemental_data: NotRequired[Optional[SupplementalDataTypedDict]] + modified_date: NotRequired[Optional[str]] + source_modified_date: NotRequired[Optional[str]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/create_connection_request.py b/sync-for-expenses/src/codat_sync_for_expenses/models/create_connection_request.py new file mode 100644 index 000000000..cd871ce94 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/create_connection_request.py @@ -0,0 +1,110 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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-expenses/src/codat_sync_for_expenses/models/create_customer_response_all_of_data.py b/sync-for-expenses/src/codat_sync_for_expenses/models/create_customer_response_all_of_data.py new file mode 100644 index 000000000..20d9f4b4f --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/create_customer_response_all_of_data.py @@ -0,0 +1,166 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.models.shared.contact import Contact, ContactTypedDict +from codat_sync_for_expenses.models.shared.customerstatus import CustomerStatus +from codat_sync_for_expenses.models.shared.items import Items, ItemsTypedDict +from codat_sync_for_expenses.models.shared.metadata import Metadata, MetadataTypedDict +from codat_sync_for_expenses.models.shared.supplementaldata import SupplementalData, SupplementalDataTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class CreateCustomerResponseAllOfData(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} + """ + CreateCustomerResponseAllOfData + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Identifier for the customer, unique to the company in the accounting software.") + customer_name: Optional[str] = Field(default=None, description="Name of the customer as recorded in the accounting system, typically the company name.", alias="customerName") + contact_name: Optional[str] = Field(default=None, description="Name of the main contact for the identified customer.", alias="contactName") + email_address: Optional[str] = Field(default=None, description="Email address the customer can be contacted by.", alias="emailAddress") + default_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.", alias="defaultCurrency") + phone: Optional[str] = Field(default=None, description="Phone number the customer can be contacted by.") + addresses: Optional[List[Items]] = Field(default=None, description="An array of Addresses.") + contacts: Optional[List[Contact]] = Field(default=None, description="An array of Contacts.") + registration_number: Optional[str] = Field(default=None, description="Company number. In the UK, this is typically the Companies House company registration number.", alias="registrationNumber") + tax_number: Optional[str] = Field(default=None, description="Company tax number.", alias="taxNumber") + status: CustomerStatus = Field(description="Current state of the customer.") + metadata: Optional[Metadata] = None + supplemental_data: Optional[SupplementalData] = Field(default=None, alias="supplementalData") + modified_date: Optional[str] = Field(default=None, description="The date when the record was last fetched from the accounting software, commerce software, or open banking provider and updated in Codat’s data cache. Use it to identify and retrieve records that have changed since your last fetch. For example, filtering `modifiedDate` to today will provide new records updated in Codat today. This date is populated for all data types except for attachments, balance sheets, company information, and profit & loss reports ([read more](https://docs.codat.io/using-the-api/modified-dates#modified-date)). In Codat's data model, dates and times are represented using the ISO 8601 standard.", alias="modifiedDate") + 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", "customerName", "contactName", "emailAddress", "defaultCurrency", "phone", "addresses", "contacts", "registrationNumber", "taxNumber", "status", "metadata", "supplementalData", "modifiedDate", "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 CreateCustomerResponseAllOfData 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 + # override the default output from pydantic by calling `to_dict()` of each item in contacts (list) + _items = [] + if self.contacts: + for _item_contacts in self.contacts: + if _item_contacts: + _items.append(_item_contacts.to_dict()) + _dict['contacts'] = _items + # override the default output from pydantic by calling `to_dict()` of metadata + if self.metadata: + _dict['metadata'] = self.metadata.to_dict() + # override the default output from pydantic by calling `to_dict()` of supplemental_data + if self.supplemental_data: + _dict['supplementalData'] = self.supplemental_data.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CreateCustomerResponseAllOfData 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"), + "customerName": obj.get("customerName"), + "contactName": obj.get("contactName"), + "emailAddress": obj.get("emailAddress"), + "defaultCurrency": obj.get("defaultCurrency"), + "phone": obj.get("phone"), + "addresses": [Items.from_dict(_item) for _item in obj["addresses"]] if obj.get("addresses") is not None else None, + "contacts": [Contact.from_dict(_item) for _item in obj["contacts"]] if obj.get("contacts") is not None else None, + "registrationNumber": obj.get("registrationNumber"), + "taxNumber": obj.get("taxNumber"), + "status": obj.get("status"), + "metadata": Metadata.from_dict(obj["metadata"]) if obj.get("metadata") is not None else None, + "supplementalData": SupplementalData.from_dict(obj["supplementalData"]) if obj.get("supplementalData") is not None else None, + "modifiedDate": obj.get("modifiedDate"), + "sourceModifiedDate": obj.get("sourceModifiedDate") + }) + return _obj + + + + + +class CreateCustomerResponseAllOfDataTypedDict(TypedDict): + """TypedDict variant of CreateCustomerResponseAllOfData, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + customer_name: NotRequired[Optional[str]] + contact_name: NotRequired[Optional[str]] + email_address: NotRequired[Optional[str]] + default_currency: NotRequired[Optional[str]] + phone: NotRequired[Optional[str]] + addresses: NotRequired[Optional[List[ItemsTypedDict]]] + contacts: NotRequired[Optional[List[ContactTypedDict]]] + registration_number: NotRequired[Optional[str]] + tax_number: NotRequired[Optional[str]] + status: NotRequired[CustomerStatus] + metadata: NotRequired[Optional[MetadataTypedDict]] + supplemental_data: NotRequired[Optional[SupplementalDataTypedDict]] + modified_date: NotRequired[Optional[str]] + source_modified_date: NotRequired[Optional[str]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/create_supplier_response_all_of_data.py b/sync-for-expenses/src/codat_sync_for_expenses/models/create_supplier_response_all_of_data.py new file mode 100644 index 000000000..614ec7f7c --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/create_supplier_response_all_of_data.py @@ -0,0 +1,155 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.models.shared.items import Items, ItemsTypedDict +from codat_sync_for_expenses.models.shared.metadata import Metadata, MetadataTypedDict +from codat_sync_for_expenses.models.shared.supplementaldata import SupplementalData, SupplementalDataTypedDict +from codat_sync_for_expenses.models.shared.supplierstatus import SupplierStatus +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class CreateSupplierResponseAllOfData(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} + """ + CreateSupplierResponseAllOfData + """ # 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: Optional[str] = Field(default=None, description="Name of the main contact for the supplier.", alias="contactName") + email_address: Optional[str] = Field(default=None, description="Email address that the supplier may be contacted on.", alias="emailAddress") + phone: Optional[str] = Field(default=None, description="Phone number that the supplier may be contacted on.") + addresses: Optional[List[Items]] = Field(default=None, description="An array of Addresses.") + registration_number: Optional[str] = Field(default=None, description="Company number of the supplier. In the UK, this is typically the company registration number issued by Companies House.", alias="registrationNumber") + tax_number: Optional[str] = Field(default=None, description="Supplier's company tax number.", alias="taxNumber") + status: SupplierStatus + default_currency: Optional[str] = Field(default=None, description="Default currency the supplier's transactional data is recorded in.", alias="defaultCurrency") + metadata: Optional[Metadata] = None + supplemental_data: Optional[SupplementalData] = Field(default=None, alias="supplementalData") + modified_date: Optional[str] = Field(default=None, description="The date when the record was last fetched from the accounting software, commerce software, or open banking provider and updated in Codat’s data cache. Use it to identify and retrieve records that have changed since your last fetch. For example, filtering `modifiedDate` to today will provide new records updated in Codat today. This date is populated for all data types except for attachments, balance sheets, company information, and profit & loss reports ([read more](https://docs.codat.io/using-the-api/modified-dates#modified-date)). In Codat's data model, dates and times are represented using the ISO 8601 standard.", alias="modifiedDate") + 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", "registrationNumber", "taxNumber", "status", "defaultCurrency", "metadata", "supplementalData", "modifiedDate", "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 CreateSupplierResponseAllOfData 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 + # override the default output from pydantic by calling `to_dict()` of metadata + if self.metadata: + _dict['metadata'] = self.metadata.to_dict() + # override the default output from pydantic by calling `to_dict()` of supplemental_data + if self.supplemental_data: + _dict['supplementalData'] = self.supplemental_data.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CreateSupplierResponseAllOfData 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": [Items.from_dict(_item) for _item in obj["addresses"]] if obj.get("addresses") is not None else None, + "registrationNumber": obj.get("registrationNumber"), + "taxNumber": obj.get("taxNumber"), + "status": obj.get("status"), + "defaultCurrency": obj.get("defaultCurrency"), + "metadata": Metadata.from_dict(obj["metadata"]) if obj.get("metadata") is not None else None, + "supplementalData": SupplementalData.from_dict(obj["supplementalData"]) if obj.get("supplementalData") is not None else None, + "modifiedDate": obj.get("modifiedDate"), + "sourceModifiedDate": obj.get("sourceModifiedDate") + }) + return _obj + + + + + +class CreateSupplierResponseAllOfDataTypedDict(TypedDict): + """TypedDict variant of CreateSupplierResponseAllOfData, 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[ItemsTypedDict]]] + registration_number: NotRequired[Optional[str]] + tax_number: NotRequired[Optional[str]] + status: SupplierStatus + default_currency: NotRequired[Optional[str]] + metadata: NotRequired[Optional[MetadataTypedDict]] + supplemental_data: NotRequired[Optional[SupplementalDataTypedDict]] + modified_date: NotRequired[Optional[str]] + source_modified_date: NotRequired[Optional[str]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/current_status.py b/sync-for-expenses/src/codat_sync_for_expenses/models/current_status.py new file mode 100644 index 000000000..5f023c517 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/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-expenses/src/codat_sync_for_expenses/models/data_statuses.py b/sync-for-expenses/src/codat_sync_for_expenses/models/data_statuses.py new file mode 100644 index 000000000..0338984b5 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/data_statuses.py @@ -0,0 +1,362 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.models.shared.datastatus import DataStatus, DataStatusTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class DataStatuses(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} + """ + DataStatuses + """ # noqa: E501 + account_transactions: Optional[DataStatus] = Field(default=None, alias="accountTransactions") + balance_sheet: Optional[DataStatus] = Field(default=None, alias="balanceSheet") + bank_accounts: Optional[DataStatus] = Field(default=None, alias="bankAccounts") + bank_transactions: Optional[DataStatus] = Field(default=None, alias="bankTransactions") + bill_credit_notes: Optional[DataStatus] = Field(default=None, alias="billCreditNotes") + bill_payments: Optional[DataStatus] = Field(default=None, alias="billPayments") + bills: Optional[DataStatus] = None + cash_flow_statement: Optional[DataStatus] = Field(default=None, alias="cashFlowStatement") + chart_of_accounts: Optional[DataStatus] = Field(default=None, alias="chartOfAccounts") + company: Optional[DataStatus] = None + credit_notes: Optional[DataStatus] = Field(default=None, alias="creditNotes") + customers: Optional[DataStatus] = None + direct_costs: Optional[DataStatus] = Field(default=None, alias="directCosts") + direct_incomes: Optional[DataStatus] = Field(default=None, alias="directIncomes") + invoices: Optional[DataStatus] = None + item_receipts: Optional[DataStatus] = Field(default=None, alias="itemReceipts") + items: Optional[DataStatus] = None + journal_entries: Optional[DataStatus] = Field(default=None, alias="journalEntries") + journals: Optional[DataStatus] = None + payment_methods: Optional[DataStatus] = Field(default=None, alias="paymentMethods") + payments: Optional[DataStatus] = None + profit_and_loss: Optional[DataStatus] = Field(default=None, alias="profitAndLoss") + purchase_orders: Optional[DataStatus] = Field(default=None, alias="purchaseOrders") + sales_orders: Optional[DataStatus] = Field(default=None, alias="salesOrders") + suppliers: Optional[DataStatus] = None + tax_rates: Optional[DataStatus] = Field(default=None, alias="taxRates") + tracking_categories: Optional[DataStatus] = Field(default=None, alias="trackingCategories") + transfers: Optional[DataStatus] = None + banking_account_balances: Optional[DataStatus] = Field(default=None, alias="banking-accountBalances") + banking_accounts: Optional[DataStatus] = Field(default=None, alias="banking-accounts") + banking_transaction_categories: Optional[DataStatus] = Field(default=None, alias="banking-transactionCategories") + banking_transactions: Optional[DataStatus] = Field(default=None, alias="banking-transactions") + commerce_company_info: Optional[DataStatus] = Field(default=None, alias="commerce-companyInfo") + commerce_customers: Optional[DataStatus] = Field(default=None, alias="commerce-customers") + commerce_disputes: Optional[DataStatus] = Field(default=None, alias="commerce-disputes") + commerce_locations: Optional[DataStatus] = Field(default=None, alias="commerce-locations") + commerce_orders: Optional[DataStatus] = Field(default=None, alias="commerce-orders") + commerce_payment_methods: Optional[DataStatus] = Field(default=None, alias="commerce-paymentMethods") + commerce_payments: Optional[DataStatus] = Field(default=None, alias="commerce-payments") + commerce_product_categories: Optional[DataStatus] = Field(default=None, alias="commerce-productCategories") + commerce_products: Optional[DataStatus] = Field(default=None, alias="commerce-products") + commerce_tax_components: Optional[DataStatus] = Field(default=None, alias="commerce-taxComponents") + commerce_transactions: Optional[DataStatus] = Field(default=None, alias="commerce-transactions") + __properties: ClassVar[List[str]] = ["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"] + + 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 DataStatuses 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_transactions + if self.account_transactions: + _dict['accountTransactions'] = self.account_transactions.to_dict() + # override the default output from pydantic by calling `to_dict()` of balance_sheet + if self.balance_sheet: + _dict['balanceSheet'] = self.balance_sheet.to_dict() + # override the default output from pydantic by calling `to_dict()` of bank_accounts + if self.bank_accounts: + _dict['bankAccounts'] = self.bank_accounts.to_dict() + # override the default output from pydantic by calling `to_dict()` of bank_transactions + if self.bank_transactions: + _dict['bankTransactions'] = self.bank_transactions.to_dict() + # override the default output from pydantic by calling `to_dict()` of bill_credit_notes + if self.bill_credit_notes: + _dict['billCreditNotes'] = self.bill_credit_notes.to_dict() + # override the default output from pydantic by calling `to_dict()` of bill_payments + if self.bill_payments: + _dict['billPayments'] = self.bill_payments.to_dict() + # override the default output from pydantic by calling `to_dict()` of bills + if self.bills: + _dict['bills'] = self.bills.to_dict() + # override the default output from pydantic by calling `to_dict()` of cash_flow_statement + if self.cash_flow_statement: + _dict['cashFlowStatement'] = self.cash_flow_statement.to_dict() + # override the default output from pydantic by calling `to_dict()` of chart_of_accounts + if self.chart_of_accounts: + _dict['chartOfAccounts'] = self.chart_of_accounts.to_dict() + # override the default output from pydantic by calling `to_dict()` of company + if self.company: + _dict['company'] = self.company.to_dict() + # override the default output from pydantic by calling `to_dict()` of credit_notes + if self.credit_notes: + _dict['creditNotes'] = self.credit_notes.to_dict() + # override the default output from pydantic by calling `to_dict()` of customers + if self.customers: + _dict['customers'] = self.customers.to_dict() + # override the default output from pydantic by calling `to_dict()` of direct_costs + if self.direct_costs: + _dict['directCosts'] = self.direct_costs.to_dict() + # override the default output from pydantic by calling `to_dict()` of direct_incomes + if self.direct_incomes: + _dict['directIncomes'] = self.direct_incomes.to_dict() + # override the default output from pydantic by calling `to_dict()` of invoices + if self.invoices: + _dict['invoices'] = self.invoices.to_dict() + # override the default output from pydantic by calling `to_dict()` of item_receipts + if self.item_receipts: + _dict['itemReceipts'] = self.item_receipts.to_dict() + # override the default output from pydantic by calling `to_dict()` of items + if self.items: + _dict['items'] = self.items.to_dict() + # override the default output from pydantic by calling `to_dict()` of journal_entries + if self.journal_entries: + _dict['journalEntries'] = self.journal_entries.to_dict() + # override the default output from pydantic by calling `to_dict()` of journals + if self.journals: + _dict['journals'] = self.journals.to_dict() + # override the default output from pydantic by calling `to_dict()` of payment_methods + if self.payment_methods: + _dict['paymentMethods'] = self.payment_methods.to_dict() + # override the default output from pydantic by calling `to_dict()` of payments + if self.payments: + _dict['payments'] = self.payments.to_dict() + # override the default output from pydantic by calling `to_dict()` of profit_and_loss + if self.profit_and_loss: + _dict['profitAndLoss'] = self.profit_and_loss.to_dict() + # override the default output from pydantic by calling `to_dict()` of purchase_orders + if self.purchase_orders: + _dict['purchaseOrders'] = self.purchase_orders.to_dict() + # override the default output from pydantic by calling `to_dict()` of sales_orders + if self.sales_orders: + _dict['salesOrders'] = self.sales_orders.to_dict() + # override the default output from pydantic by calling `to_dict()` of suppliers + if self.suppliers: + _dict['suppliers'] = self.suppliers.to_dict() + # override the default output from pydantic by calling `to_dict()` of tax_rates + if self.tax_rates: + _dict['taxRates'] = self.tax_rates.to_dict() + # override the default output from pydantic by calling `to_dict()` of tracking_categories + if self.tracking_categories: + _dict['trackingCategories'] = self.tracking_categories.to_dict() + # override the default output from pydantic by calling `to_dict()` of transfers + if self.transfers: + _dict['transfers'] = self.transfers.to_dict() + # override the default output from pydantic by calling `to_dict()` of banking_account_balances + if self.banking_account_balances: + _dict['banking-accountBalances'] = self.banking_account_balances.to_dict() + # override the default output from pydantic by calling `to_dict()` of banking_accounts + if self.banking_accounts: + _dict['banking-accounts'] = self.banking_accounts.to_dict() + # override the default output from pydantic by calling `to_dict()` of banking_transaction_categories + if self.banking_transaction_categories: + _dict['banking-transactionCategories'] = self.banking_transaction_categories.to_dict() + # override the default output from pydantic by calling `to_dict()` of banking_transactions + if self.banking_transactions: + _dict['banking-transactions'] = self.banking_transactions.to_dict() + # override the default output from pydantic by calling `to_dict()` of commerce_company_info + if self.commerce_company_info: + _dict['commerce-companyInfo'] = self.commerce_company_info.to_dict() + # override the default output from pydantic by calling `to_dict()` of commerce_customers + if self.commerce_customers: + _dict['commerce-customers'] = self.commerce_customers.to_dict() + # override the default output from pydantic by calling `to_dict()` of commerce_disputes + if self.commerce_disputes: + _dict['commerce-disputes'] = self.commerce_disputes.to_dict() + # override the default output from pydantic by calling `to_dict()` of commerce_locations + if self.commerce_locations: + _dict['commerce-locations'] = self.commerce_locations.to_dict() + # override the default output from pydantic by calling `to_dict()` of commerce_orders + if self.commerce_orders: + _dict['commerce-orders'] = self.commerce_orders.to_dict() + # override the default output from pydantic by calling `to_dict()` of commerce_payment_methods + if self.commerce_payment_methods: + _dict['commerce-paymentMethods'] = self.commerce_payment_methods.to_dict() + # override the default output from pydantic by calling `to_dict()` of commerce_payments + if self.commerce_payments: + _dict['commerce-payments'] = self.commerce_payments.to_dict() + # override the default output from pydantic by calling `to_dict()` of commerce_product_categories + if self.commerce_product_categories: + _dict['commerce-productCategories'] = self.commerce_product_categories.to_dict() + # override the default output from pydantic by calling `to_dict()` of commerce_products + if self.commerce_products: + _dict['commerce-products'] = self.commerce_products.to_dict() + # override the default output from pydantic by calling `to_dict()` of commerce_tax_components + if self.commerce_tax_components: + _dict['commerce-taxComponents'] = self.commerce_tax_components.to_dict() + # override the default output from pydantic by calling `to_dict()` of commerce_transactions + if self.commerce_transactions: + _dict['commerce-transactions'] = self.commerce_transactions.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of DataStatuses from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "accountTransactions": DataStatus.from_dict(obj["accountTransactions"]) if obj.get("accountTransactions") is not None else None, + "balanceSheet": DataStatus.from_dict(obj["balanceSheet"]) if obj.get("balanceSheet") is not None else None, + "bankAccounts": DataStatus.from_dict(obj["bankAccounts"]) if obj.get("bankAccounts") is not None else None, + "bankTransactions": DataStatus.from_dict(obj["bankTransactions"]) if obj.get("bankTransactions") is not None else None, + "billCreditNotes": DataStatus.from_dict(obj["billCreditNotes"]) if obj.get("billCreditNotes") is not None else None, + "billPayments": DataStatus.from_dict(obj["billPayments"]) if obj.get("billPayments") is not None else None, + "bills": DataStatus.from_dict(obj["bills"]) if obj.get("bills") is not None else None, + "cashFlowStatement": DataStatus.from_dict(obj["cashFlowStatement"]) if obj.get("cashFlowStatement") is not None else None, + "chartOfAccounts": DataStatus.from_dict(obj["chartOfAccounts"]) if obj.get("chartOfAccounts") is not None else None, + "company": DataStatus.from_dict(obj["company"]) if obj.get("company") is not None else None, + "creditNotes": DataStatus.from_dict(obj["creditNotes"]) if obj.get("creditNotes") is not None else None, + "customers": DataStatus.from_dict(obj["customers"]) if obj.get("customers") is not None else None, + "directCosts": DataStatus.from_dict(obj["directCosts"]) if obj.get("directCosts") is not None else None, + "directIncomes": DataStatus.from_dict(obj["directIncomes"]) if obj.get("directIncomes") is not None else None, + "invoices": DataStatus.from_dict(obj["invoices"]) if obj.get("invoices") is not None else None, + "itemReceipts": DataStatus.from_dict(obj["itemReceipts"]) if obj.get("itemReceipts") is not None else None, + "items": DataStatus.from_dict(obj["items"]) if obj.get("items") is not None else None, + "journalEntries": DataStatus.from_dict(obj["journalEntries"]) if obj.get("journalEntries") is not None else None, + "journals": DataStatus.from_dict(obj["journals"]) if obj.get("journals") is not None else None, + "paymentMethods": DataStatus.from_dict(obj["paymentMethods"]) if obj.get("paymentMethods") is not None else None, + "payments": DataStatus.from_dict(obj["payments"]) if obj.get("payments") is not None else None, + "profitAndLoss": DataStatus.from_dict(obj["profitAndLoss"]) if obj.get("profitAndLoss") is not None else None, + "purchaseOrders": DataStatus.from_dict(obj["purchaseOrders"]) if obj.get("purchaseOrders") is not None else None, + "salesOrders": DataStatus.from_dict(obj["salesOrders"]) if obj.get("salesOrders") is not None else None, + "suppliers": DataStatus.from_dict(obj["suppliers"]) if obj.get("suppliers") is not None else None, + "taxRates": DataStatus.from_dict(obj["taxRates"]) if obj.get("taxRates") is not None else None, + "trackingCategories": DataStatus.from_dict(obj["trackingCategories"]) if obj.get("trackingCategories") is not None else None, + "transfers": DataStatus.from_dict(obj["transfers"]) if obj.get("transfers") is not None else None, + "banking-accountBalances": DataStatus.from_dict(obj["banking-accountBalances"]) if obj.get("banking-accountBalances") is not None else None, + "banking-accounts": DataStatus.from_dict(obj["banking-accounts"]) if obj.get("banking-accounts") is not None else None, + "banking-transactionCategories": DataStatus.from_dict(obj["banking-transactionCategories"]) if obj.get("banking-transactionCategories") is not None else None, + "banking-transactions": DataStatus.from_dict(obj["banking-transactions"]) if obj.get("banking-transactions") is not None else None, + "commerce-companyInfo": DataStatus.from_dict(obj["commerce-companyInfo"]) if obj.get("commerce-companyInfo") is not None else None, + "commerce-customers": DataStatus.from_dict(obj["commerce-customers"]) if obj.get("commerce-customers") is not None else None, + "commerce-disputes": DataStatus.from_dict(obj["commerce-disputes"]) if obj.get("commerce-disputes") is not None else None, + "commerce-locations": DataStatus.from_dict(obj["commerce-locations"]) if obj.get("commerce-locations") is not None else None, + "commerce-orders": DataStatus.from_dict(obj["commerce-orders"]) if obj.get("commerce-orders") is not None else None, + "commerce-paymentMethods": DataStatus.from_dict(obj["commerce-paymentMethods"]) if obj.get("commerce-paymentMethods") is not None else None, + "commerce-payments": DataStatus.from_dict(obj["commerce-payments"]) if obj.get("commerce-payments") is not None else None, + "commerce-productCategories": DataStatus.from_dict(obj["commerce-productCategories"]) if obj.get("commerce-productCategories") is not None else None, + "commerce-products": DataStatus.from_dict(obj["commerce-products"]) if obj.get("commerce-products") is not None else None, + "commerce-taxComponents": DataStatus.from_dict(obj["commerce-taxComponents"]) if obj.get("commerce-taxComponents") is not None else None, + "commerce-transactions": DataStatus.from_dict(obj["commerce-transactions"]) if obj.get("commerce-transactions") is not None else None + }) + return _obj + + + + +# Speakeasy response-class alias — type-identical so isinstance() checks pass. +GetDataStatusDataStatuses = DataStatuses + + + +class DataStatusesTypedDict(TypedDict): + """TypedDict variant of DataStatuses, for dict-literal request/response inputs.""" + account_transactions: NotRequired[Optional[DataStatusTypedDict]] + balance_sheet: NotRequired[Optional[DataStatusTypedDict]] + bank_accounts: NotRequired[Optional[DataStatusTypedDict]] + bank_transactions: NotRequired[Optional[DataStatusTypedDict]] + bill_credit_notes: NotRequired[Optional[DataStatusTypedDict]] + bill_payments: NotRequired[Optional[DataStatusTypedDict]] + bills: NotRequired[Optional[DataStatusTypedDict]] + cash_flow_statement: NotRequired[Optional[DataStatusTypedDict]] + chart_of_accounts: NotRequired[Optional[DataStatusTypedDict]] + company: NotRequired[Optional[DataStatusTypedDict]] + credit_notes: NotRequired[Optional[DataStatusTypedDict]] + customers: NotRequired[Optional[DataStatusTypedDict]] + direct_costs: NotRequired[Optional[DataStatusTypedDict]] + direct_incomes: NotRequired[Optional[DataStatusTypedDict]] + invoices: NotRequired[Optional[DataStatusTypedDict]] + item_receipts: NotRequired[Optional[DataStatusTypedDict]] + items: NotRequired[Optional[DataStatusTypedDict]] + journal_entries: NotRequired[Optional[DataStatusTypedDict]] + journals: NotRequired[Optional[DataStatusTypedDict]] + payment_methods: NotRequired[Optional[DataStatusTypedDict]] + payments: NotRequired[Optional[DataStatusTypedDict]] + profit_and_loss: NotRequired[Optional[DataStatusTypedDict]] + purchase_orders: NotRequired[Optional[DataStatusTypedDict]] + sales_orders: NotRequired[Optional[DataStatusTypedDict]] + suppliers: NotRequired[Optional[DataStatusTypedDict]] + tax_rates: NotRequired[Optional[DataStatusTypedDict]] + tracking_categories: NotRequired[Optional[DataStatusTypedDict]] + transfers: NotRequired[Optional[DataStatusTypedDict]] + banking_account_balances: NotRequired[Optional[DataStatusTypedDict]] + banking_accounts: NotRequired[Optional[DataStatusTypedDict]] + banking_transaction_categories: NotRequired[Optional[DataStatusTypedDict]] + banking_transactions: NotRequired[Optional[DataStatusTypedDict]] + commerce_company_info: NotRequired[Optional[DataStatusTypedDict]] + commerce_customers: NotRequired[Optional[DataStatusTypedDict]] + commerce_disputes: NotRequired[Optional[DataStatusTypedDict]] + commerce_locations: NotRequired[Optional[DataStatusTypedDict]] + commerce_orders: NotRequired[Optional[DataStatusTypedDict]] + commerce_payment_methods: NotRequired[Optional[DataStatusTypedDict]] + commerce_payments: NotRequired[Optional[DataStatusTypedDict]] + commerce_product_categories: NotRequired[Optional[DataStatusTypedDict]] + commerce_products: NotRequired[Optional[DataStatusTypedDict]] + commerce_tax_components: NotRequired[Optional[DataStatusTypedDict]] + commerce_transactions: NotRequired[Optional[DataStatusTypedDict]] + +# Speakeasy TypedDict companions for response-class aliases. +GetDataStatusDataStatusesTypedDict = DataStatusesTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/data_types.py b/sync-for-expenses/src/codat_sync_for_expenses/models/data_types.py new file mode 100644 index 000000000..734060127 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/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-expenses/src/codat_sync_for_expenses/models/dataset_status.py b/sync-for-expenses/src/codat_sync_for_expenses/models/dataset_status.py new file mode 100644 index 000000000..2b657c709 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/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-expenses/src/codat_sync_for_expenses/models/error_message.py b/sync-for-expenses/src/codat_sync_for_expenses/models/error_message.py new file mode 100644 index 000000000..8aea58e89 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/error_message.py @@ -0,0 +1,121 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.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-expenses/src/codat_sync_for_expenses/models/error_status.py b/sync-for-expenses/src/codat_sync_for_expenses/models/error_status.py new file mode 100644 index 000000000..ecf0a01b7 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/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-expenses/src/codat_sync_for_expenses/models/errors/__init__.py b/sync-for-expenses/src/codat_sync_for_expenses/models/errors/__init__.py index a7c0be6a5..aaaf02582 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/errors/__init__.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/errors/__init__.py @@ -1,39 +1,16 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.errors — Speakeasy-shape exception hierarchy.""" from .codatsyncexpenseserror import CodatSyncExpensesError -from typing import Any, TYPE_CHECKING - -from codat_sync_for_expenses.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__ = [ "CodatSyncExpensesError", + "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-expenses/src/codat_sync_for_expenses/models/errors/codatsyncexpenseserror.py b/sync-for-expenses/src/codat_sync_for_expenses/models/errors/codatsyncexpenseserror.py index 36f9c6914..0e5b106b2 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/errors/codatsyncexpenseserror.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/errors/codatsyncexpenseserror.py @@ -1,30 +1,72 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""Base error class for codat_sync_for_expenses. -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 CodatSyncExpensesError(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 + # (`CodatSyncExpensesError(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-expenses/src/codat_sync_for_expenses/models/errors/errormessage.py b/sync-for-expenses/src/codat_sync_for_expenses/models/errors/errormessage.py index 0afb6562e..2c114fbca 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/errors/errormessage.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/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_expenses.models.errors import CodatSyncExpensesError -from codat_sync_for_expenses.models.shared import ( - errorvalidation as shared_errorvalidation, -) -from codat_sync_for_expenses.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): - can_be_retried: Annotated[Optional[str], pydantic.Field(alias="canBeRetried")] = ( - None - ) - r"""`True` if the error occurred transiently and can be retried.""" - 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.""" - 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.""" - error: Optional[str] = None - r"""A brief description of the error.""" - service: Optional[str] = None - r"""Codat's service the returned the error.""" - status_code: Annotated[Optional[int], pydantic.Field(alias="statusCode")] = None - r"""The HTTP status code returned by 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.""" - - -@dataclass(unsafe_hash=True) + +from typing import Any, Mapping, Optional + +from .codatsyncexpenseserror import CodatSyncExpensesError +from codat_sync_for_expenses.models.error_message import ErrorMessage as ErrorMessageData + + class ErrorMessage(CodatSyncExpensesError): - 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-expenses/src/codat_sync_for_expenses/models/errors/no_response_error.py b/sync-for-expenses/src/codat_sync_for_expenses/models/errors/no_response_error.py index 1deab64bc..acea02af8 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/errors/no_response_error.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/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-expenses/src/codat_sync_for_expenses/models/errors/responsevalidationerror.py b/sync-for-expenses/src/codat_sync_for_expenses/models/errors/responsevalidationerror.py index 129dfa81c..c4cfce17b 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/errors/responsevalidationerror.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/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_expenses.models.errors import CodatSyncExpensesError +from typing import Any, Mapping, Optional + +from .codatsyncexpenseserror import CodatSyncExpensesError -@dataclass(unsafe_hash=True) class ResponseValidationError(CodatSyncExpensesError): - """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-expenses/src/codat_sync_for_expenses/models/errors/sdkerror.py b/sync-for-expenses/src/codat_sync_for_expenses/models/errors/sdkerror.py index 9eb94a8ab..dfe32ca94 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/errors/sdkerror.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/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 .codatsyncexpenseserror import CodatSyncExpensesError -from codat_sync_for_expenses.models.errors import CodatSyncExpensesError MAX_MESSAGE_LEN = 10_000 -@dataclass(unsafe_hash=True) class SDKError(CodatSyncExpensesError): """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-expenses/src/codat_sync_for_expenses/models/expense_contact_ref.py b/sync-for-expenses/src/codat_sync_for_expenses/models/expense_contact_ref.py new file mode 100644 index 000000000..decd49a32 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/expense_contact_ref.py @@ -0,0 +1,114 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.models.type import Type +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_expenses.models._compat.expensecontactref import ExpenseContactRefType +class ExpenseContactRef(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} + """ + ExpenseContactRef + """ # noqa: E501 + id: str = Field(description="Identifier of supplier or customer.") + type: Optional[ExpenseContactRefType] = Field(default='Supplier', description="The type of contact.") + __properties: ClassVar[List[str]] = ["id", "type"] + + @field_validator('type') + def type_validate_enum(cls, value): + """Validates the enum""" + if value is None: + return value + + if value not in set(['Supplier']): + raise ValueError("must be one of enum values ('Supplier')") + 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 ExpenseContactRef 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 ExpenseContactRef 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") if obj.get("type") is not None else 'Supplier' + }) + return _obj + + + + + +class ExpenseContactRefTypedDict(TypedDict): + """TypedDict variant of ExpenseContactRef, for dict-literal request/response inputs.""" + id: NotRequired[str] + type: NotRequired[Optional[ExpenseContactRefType]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/expense_transaction_type.py b/sync-for-expenses/src/codat_sync_for_expenses/models/expense_transaction_type.py new file mode 100644 index 000000000..89541804f --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/expense_transaction_type.py @@ -0,0 +1,11 @@ +from __future__ import annotations + +from enum import Enum + + +class ExpenseTransactionType(str, Enum): + """ExpenseTransactionType enum (lifted from inline OAS enum).""" + PAYMENT = 'Payment' + REFUND = 'Refund' + REWARD = 'Reward' + CHARGEBACK = 'Chargeback' diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/expenses_sync_webhook_status.py b/sync-for-expenses/src/codat_sync_for_expenses/models/expenses_sync_webhook_status.py new file mode 100644 index 000000000..63d69d1a0 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/expenses_sync_webhook_status.py @@ -0,0 +1,12 @@ +from __future__ import annotations + +from enum import Enum + + +class ExpensesSyncWebhookStatus(str, Enum): + """ExpensesSyncWebhookStatus enum (lifted from inline OAS enum).""" + UNKNOWN = 'Unknown' + PUSH_ERROR = 'PushError' + COMPLETED = 'Completed' + FAILED = 'Failed' + PENDING = 'Pending' diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/invoice_to_type.py b/sync-for-expenses/src/codat_sync_for_expenses/models/invoice_to_type.py new file mode 100644 index 000000000..52d34441f --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/invoice_to_type.py @@ -0,0 +1,8 @@ +from __future__ import annotations + +from enum import Enum + + +class InvoiceToType(str, Enum): + """InvoiceToType enum (lifted from inline OAS enum).""" + CUSTOMER = 'customer' diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/model3.py b/sync-for-expenses/src/codat_sync_for_expenses/models/model3.py new file mode 100644 index 000000000..f74307a20 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/model3.py @@ -0,0 +1,102 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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 Model3(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} + """ + Model3 + """ # noqa: E501 + modified_date: Optional[str] = Field(default=None, description="The date when the record was last fetched from the accounting software, commerce software, or open banking provider and updated in Codat’s data cache. Use it to identify and retrieve records that have changed since your last fetch. For example, filtering `modifiedDate` to today will provide new records updated in Codat today. This date is populated for all data types except for attachments, balance sheets, company information, and profit & loss reports ([read more](https://docs.codat.io/using-the-api/modified-dates#modified-date)). In Codat's data model, dates and times are represented using the ISO 8601 standard.", alias="modifiedDate") + 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]] = ["modifiedDate", "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 Model3 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 Model3 from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "modifiedDate": obj.get("modifiedDate"), + "sourceModifiedDate": obj.get("sourceModifiedDate") + }) + return _obj + + + + + +class Model3TypedDict(TypedDict): + """TypedDict variant of Model3, for dict-literal request/response inputs.""" + modified_date: NotRequired[Optional[str]] + source_modified_date: NotRequired[Optional[str]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/__init__.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/__init__.py index bd69bd0ce..328ca4482 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/__init__.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/__init__.py @@ -1,360 +1,154 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations — re-exports of per-operation request envelopes.""" -from typing import Any, TYPE_CHECKING +from codat_sync_for_expenses.api.accounts import ( + CreateAccountRequest, + CreateAccountRequestTypedDict, + GetCreateChartOfAccountsModelRequest, + GetCreateChartOfAccountsModelRequestTypedDict, +) +from codat_sync_for_expenses.api.adjustments import ( + CreateAdjustmentTransactionRequest, + CreateAdjustmentTransactionRequestTypedDict, +) +from codat_sync_for_expenses.api.attachments import ( + UploadExpenseAttachmentRequest, + UploadExpenseAttachmentRequestTypedDict, +) +from codat_sync_for_expenses.api.bank_accounts import ( + CreateBankAccountRequest, + CreateBankAccountRequestTypedDict, + GetCreateBankAccountsModelRequest, + GetCreateBankAccountsModelRequestTypedDict, +) +from codat_sync_for_expenses.api.companies import ( + CreateCompanyRequest, + CreateCompanyRequestTypedDict, + DeleteCompanyRequest, + DeleteCompanyRequestTypedDict, + GetCompanyRequest, + GetCompanyRequestTypedDict, + ListCompaniesRequest, + ListCompaniesRequestTypedDict, + ReplaceCompanyRequest, + ReplaceCompanyRequestTypedDict, + UpdateCompanyRequest, + UpdateCompanyRequestTypedDict, +) +from codat_sync_for_expenses.api.company_info import ( + GetCompanyInfoRequest, + GetCompanyInfoRequestTypedDict, +) +from codat_sync_for_expenses.api.configuration import ( + GetCompanyConfigurationRequest, + GetCompanyConfigurationRequestTypedDict, + SetCompanyConfigurationRequest, + SetCompanyConfigurationRequestTypedDict, +) +from codat_sync_for_expenses.api.connections import ( + CreateConnectionRequest, + CreateConnectionRequestTypedDict, + CreatePartnerExpenseConnectionRequest, + CreatePartnerExpenseConnectionRequestTypedDict, + DeleteConnectionRequest, + DeleteConnectionRequestTypedDict, + GetConnectionRequest, + GetConnectionRequestTypedDict, + ListConnectionsRequest, + ListConnectionsRequestTypedDict, + UnlinkConnectionRequest, + UnlinkConnectionRequestTypedDict, +) +from codat_sync_for_expenses.api.customers import ( + CreateCustomerRequest, + CreateCustomerRequestTypedDict, + GetCustomerRequest, + GetCustomerRequestTypedDict, + ListCustomersRequest, + ListCustomersRequestTypedDict, + UpdateCustomerRequest, + UpdateCustomerRequestTypedDict, +) +from codat_sync_for_expenses.api.expenses import ( + CreateExpenseTransactionRequest, + CreateExpenseTransactionRequestTypedDict, + UpdateExpenseTransactionRequest, + UpdateExpenseTransactionRequestTypedDict, +) +from codat_sync_for_expenses.api.manage_data import ( + GetDataStatusRequest, + GetDataStatusRequestTypedDict, + GetPullOperationRequest, + GetPullOperationRequestTypedDict, + ListPullOperationsRequest, + ListPullOperationsRequestTypedDict, + RefreshAllDataTypesRequest, + RefreshAllDataTypesRequestTypedDict, + RefreshDataTypeRequest, + RefreshDataTypeRequestTypedDict, +) +from codat_sync_for_expenses.api.mapping_options import ( + GetMappingOptionsRequest, + GetMappingOptionsRequestTypedDict, +) +from codat_sync_for_expenses.api.push_operations import ( + GetPushOperationRequest, + GetPushOperationRequestTypedDict, + ListPushOperationsRequest, + ListPushOperationsRequestTypedDict, +) +from codat_sync_for_expenses.api.reimbursements import ( + CreateReimbursableExpenseTransactionRequest, + CreateReimbursableExpenseTransactionRequestTypedDict, + UpdateReimbursableExpenseTransactionRequest, + UpdateReimbursableExpenseTransactionRequestTypedDict, +) +from codat_sync_for_expenses.api.suppliers import ( + CreateSupplierRequest, + CreateSupplierRequestTypedDict, + GetSupplierRequest, + GetSupplierRequestTypedDict, + ListSuppliersRequest, + ListSuppliersRequestTypedDict, + UpdateSupplierRequest, + UpdateSupplierRequestTypedDict, +) +from codat_sync_for_expenses.api.sync import ( + GetLastSuccessfulSyncRequest, + GetLastSuccessfulSyncRequestTypedDict, + GetLatestSyncRequest, + GetLatestSyncRequestTypedDict, + GetSyncByIDRequest, + GetSyncByIDRequest as GetSyncByIdRequest, + GetSyncByIDRequestTypedDict, + GetSyncByIDRequestTypedDict as GetSyncByIdRequestTypedDict, + ListSyncsRequest, + ListSyncsRequestTypedDict, +) +from codat_sync_for_expenses.api.transaction_status import ( + GetSyncTransactionRequest, + GetSyncTransactionRequestTypedDict, + ListSyncTransactionsRequest, + ListSyncTransactionsRequestTypedDict, +) +from codat_sync_for_expenses.api.transfers import ( + CreateTransferTransactionRequest, + CreateTransferTransactionRequestTypedDict, +) -from codat_sync_for_expenses.utils.dynamic_imports import lazy_getattr, lazy_dir +# Speakeasy request-body class names (aliases to POC body classes). +from codat_sync_for_expenses.models.shared.adjustmenttransactionrequest import AdjustmentTransactionRequest as CreateAdjustmentTransactionAdjustmentTransactionRequest +from codat_sync_for_expenses.models.create_connection_request import CreateConnectionRequest as CreateConnectionRequestBody +from codat_sync_for_expenses.models.shared.expensetransaction import ExpenseTransaction as CreateExpenseTransactionExpenseTransaction +from codat_sync_for_expenses.models.shared.reimbursableexpensetransaction import ReimbursableExpenseTransaction as CreateReimbursableExpenseTransactionReimbursableExpenseTransaction +from codat_sync_for_expenses.models.update_connection import UpdateConnection as UnlinkConnectionUpdateConnection -if TYPE_CHECKING: - from .create_account import CreateAccountRequest, CreateAccountRequestTypedDict - from .create_adjustment_transaction import ( - CreateAdjustmentTransactionRequest, - CreateAdjustmentTransactionRequestTypedDict, - ) - from .create_bank_account import ( - CreateBankAccountRequest, - CreateBankAccountRequestTypedDict, - ) - from .create_connection import ( - CreateConnectionRequest, - CreateConnectionRequestBody, - CreateConnectionRequestBodyTypedDict, - CreateConnectionRequestTypedDict, - ) - from .create_customer import CreateCustomerRequest, CreateCustomerRequestTypedDict - from .create_expense_transaction import ( - CreateExpenseTransactionRequest, - CreateExpenseTransactionRequestTypedDict, - ) - from .create_partner_expense_connection import ( - CreatePartnerExpenseConnectionRequest, - CreatePartnerExpenseConnectionRequestTypedDict, - ) - from .create_reimbursable_expense_transaction import ( - CreateReimbursableExpenseTransactionRequest, - CreateReimbursableExpenseTransactionRequestTypedDict, - ) - from .create_supplier import CreateSupplierRequest, CreateSupplierRequestTypedDict - from .create_transfer_transaction import ( - CreateTransferTransactionRequest, - CreateTransferTransactionRequestTypedDict, - ) - from .delete_company import DeleteCompanyRequest, DeleteCompanyRequestTypedDict - from .delete_connection import ( - DeleteConnectionRequest, - DeleteConnectionRequestTypedDict, - ) - from .get_company import GetCompanyRequest, GetCompanyRequestTypedDict - from .get_company_configuration import ( - GetCompanyConfigurationRequest, - GetCompanyConfigurationRequestTypedDict, - ) - from .get_company_info import GetCompanyInfoRequest, GetCompanyInfoRequestTypedDict - from .get_connection import GetConnectionRequest, GetConnectionRequestTypedDict - from .get_create_bankaccounts_model import ( - GetCreateBankAccountsModelRequest, - GetCreateBankAccountsModelRequestTypedDict, - ) - from .get_create_chartofaccounts_model import ( - GetCreateChartOfAccountsModelRequest, - GetCreateChartOfAccountsModelRequestTypedDict, - ) - from .get_customer import GetCustomerRequest, GetCustomerRequestTypedDict - from .get_data_status import ( - GetDataStatusDataStatuses, - GetDataStatusDataStatusesTypedDict, - GetDataStatusRequest, - GetDataStatusRequestTypedDict, - ) - from .get_last_successful_sync import ( - GetLastSuccessfulSyncRequest, - GetLastSuccessfulSyncRequestTypedDict, - ) - from .get_latest_sync import GetLatestSyncRequest, GetLatestSyncRequestTypedDict - from .get_mapping_options import ( - GetMappingOptionsRequest, - GetMappingOptionsRequestTypedDict, - ) - from .get_pull_operation import ( - GetPullOperationRequest, - GetPullOperationRequestTypedDict, - ) - from .get_push_operation import ( - GetPushOperationRequest, - GetPushOperationRequestTypedDict, - ) - from .get_supplier import GetSupplierRequest, GetSupplierRequestTypedDict - from .get_sync_by_id import GetSyncByIDRequest, GetSyncByIDRequestTypedDict - from .get_sync_transaction import ( - GetSyncTransactionRequest, - GetSyncTransactionRequestTypedDict, - ) - from .list_companies import ListCompaniesRequest, ListCompaniesRequestTypedDict - from .list_connections import ( - ListConnectionsRequest, - ListConnectionsRequestTypedDict, - ) - from .list_customers import ListCustomersRequest, ListCustomersRequestTypedDict - from .list_pull_operations import ( - ListPullOperationsRequest, - ListPullOperationsRequestTypedDict, - ) - from .list_push_operations import ( - ListPushOperationsRequest, - ListPushOperationsRequestTypedDict, - ) - from .list_suppliers import ListSuppliersRequest, ListSuppliersRequestTypedDict - from .list_sync_transactions import ( - ListSyncTransactionsRequest, - ListSyncTransactionsRequestTypedDict, - ) - from .list_syncs import ListSyncsRequest, ListSyncsRequestTypedDict - from .refresh_all_data_types import ( - RefreshAllDataTypesRequest, - RefreshAllDataTypesRequestTypedDict, - ) - from .refresh_data_type import ( - RefreshDataTypeRequest, - RefreshDataTypeRequestTypedDict, - ) - from .replace_company import ReplaceCompanyRequest, ReplaceCompanyRequestTypedDict - from .set_company_configuration import ( - SetCompanyConfigurationRequest, - SetCompanyConfigurationRequestTypedDict, - ) - from .unlink_connection import ( - UnlinkConnectionRequest, - UnlinkConnectionRequestTypedDict, - UnlinkConnectionUpdateConnection, - UnlinkConnectionUpdateConnectionTypedDict, - ) - from .update_company import UpdateCompanyRequest, UpdateCompanyRequestTypedDict - from .update_customer import UpdateCustomerRequest, UpdateCustomerRequestTypedDict - from .update_expense_transaction import ( - UpdateExpenseTransactionRequest, - UpdateExpenseTransactionRequestTypedDict, - ) - from .update_reimbursable_expense_transaction import ( - UpdateReimbursableExpenseTransactionRequest, - UpdateReimbursableExpenseTransactionRequestTypedDict, - ) - from .update_supplier import UpdateSupplierRequest, UpdateSupplierRequestTypedDict - from .upload_expense_attachment import ( - UploadExpenseAttachmentRequest, - UploadExpenseAttachmentRequestTypedDict, - ) +# Speakeasy operations names POC defines elsewhere (response bodies, op-param enums). +from codat_sync_for_expenses.models.data_statuses import GetDataStatusDataStatuses -__all__ = [ - "CreateAccountRequest", - "CreateAccountRequestTypedDict", - "CreateAdjustmentTransactionRequest", - "CreateAdjustmentTransactionRequestTypedDict", - "CreateBankAccountRequest", - "CreateBankAccountRequestTypedDict", - "CreateConnectionRequest", - "CreateConnectionRequestBody", - "CreateConnectionRequestBodyTypedDict", - "CreateConnectionRequestTypedDict", - "CreateCustomerRequest", - "CreateCustomerRequestTypedDict", - "CreateExpenseTransactionRequest", - "CreateExpenseTransactionRequestTypedDict", - "CreatePartnerExpenseConnectionRequest", - "CreatePartnerExpenseConnectionRequestTypedDict", - "CreateReimbursableExpenseTransactionRequest", - "CreateReimbursableExpenseTransactionRequestTypedDict", - "CreateSupplierRequest", - "CreateSupplierRequestTypedDict", - "CreateTransferTransactionRequest", - "CreateTransferTransactionRequestTypedDict", - "DeleteCompanyRequest", - "DeleteCompanyRequestTypedDict", - "DeleteConnectionRequest", - "DeleteConnectionRequestTypedDict", - "GetCompanyConfigurationRequest", - "GetCompanyConfigurationRequestTypedDict", - "GetCompanyInfoRequest", - "GetCompanyInfoRequestTypedDict", - "GetCompanyRequest", - "GetCompanyRequestTypedDict", - "GetConnectionRequest", - "GetConnectionRequestTypedDict", - "GetCreateBankAccountsModelRequest", - "GetCreateBankAccountsModelRequestTypedDict", - "GetCreateChartOfAccountsModelRequest", - "GetCreateChartOfAccountsModelRequestTypedDict", - "GetCustomerRequest", - "GetCustomerRequestTypedDict", - "GetDataStatusDataStatuses", - "GetDataStatusDataStatusesTypedDict", - "GetDataStatusRequest", - "GetDataStatusRequestTypedDict", - "GetLastSuccessfulSyncRequest", - "GetLastSuccessfulSyncRequestTypedDict", - "GetLatestSyncRequest", - "GetLatestSyncRequestTypedDict", - "GetMappingOptionsRequest", - "GetMappingOptionsRequestTypedDict", - "GetPullOperationRequest", - "GetPullOperationRequestTypedDict", - "GetPushOperationRequest", - "GetPushOperationRequestTypedDict", - "GetSupplierRequest", - "GetSupplierRequestTypedDict", - "GetSyncByIDRequest", - "GetSyncByIDRequestTypedDict", - "GetSyncTransactionRequest", - "GetSyncTransactionRequestTypedDict", - "ListCompaniesRequest", - "ListCompaniesRequestTypedDict", - "ListConnectionsRequest", - "ListConnectionsRequestTypedDict", - "ListCustomersRequest", - "ListCustomersRequestTypedDict", - "ListPullOperationsRequest", - "ListPullOperationsRequestTypedDict", - "ListPushOperationsRequest", - "ListPushOperationsRequestTypedDict", - "ListSuppliersRequest", - "ListSuppliersRequestTypedDict", - "ListSyncTransactionsRequest", - "ListSyncTransactionsRequestTypedDict", - "ListSyncsRequest", - "ListSyncsRequestTypedDict", - "RefreshAllDataTypesRequest", - "RefreshAllDataTypesRequestTypedDict", - "RefreshDataTypeRequest", - "RefreshDataTypeRequestTypedDict", - "ReplaceCompanyRequest", - "ReplaceCompanyRequestTypedDict", - "SetCompanyConfigurationRequest", - "SetCompanyConfigurationRequestTypedDict", - "UnlinkConnectionRequest", - "UnlinkConnectionRequestTypedDict", - "UnlinkConnectionUpdateConnection", - "UnlinkConnectionUpdateConnectionTypedDict", - "UpdateCompanyRequest", - "UpdateCompanyRequestTypedDict", - "UpdateCustomerRequest", - "UpdateCustomerRequestTypedDict", - "UpdateExpenseTransactionRequest", - "UpdateExpenseTransactionRequestTypedDict", - "UpdateReimbursableExpenseTransactionRequest", - "UpdateReimbursableExpenseTransactionRequestTypedDict", - "UpdateSupplierRequest", - "UpdateSupplierRequestTypedDict", - "UploadExpenseAttachmentRequest", - "UploadExpenseAttachmentRequestTypedDict", -] - -_dynamic_imports: dict[str, str] = { - "CreateAccountRequest": ".create_account", - "CreateAccountRequestTypedDict": ".create_account", - "CreateAdjustmentTransactionRequest": ".create_adjustment_transaction", - "CreateAdjustmentTransactionRequestTypedDict": ".create_adjustment_transaction", - "CreateBankAccountRequest": ".create_bank_account", - "CreateBankAccountRequestTypedDict": ".create_bank_account", - "CreateConnectionRequest": ".create_connection", - "CreateConnectionRequestBody": ".create_connection", - "CreateConnectionRequestBodyTypedDict": ".create_connection", - "CreateConnectionRequestTypedDict": ".create_connection", - "CreateCustomerRequest": ".create_customer", - "CreateCustomerRequestTypedDict": ".create_customer", - "CreateExpenseTransactionRequest": ".create_expense_transaction", - "CreateExpenseTransactionRequestTypedDict": ".create_expense_transaction", - "CreatePartnerExpenseConnectionRequest": ".create_partner_expense_connection", - "CreatePartnerExpenseConnectionRequestTypedDict": ".create_partner_expense_connection", - "CreateReimbursableExpenseTransactionRequest": ".create_reimbursable_expense_transaction", - "CreateReimbursableExpenseTransactionRequestTypedDict": ".create_reimbursable_expense_transaction", - "CreateSupplierRequest": ".create_supplier", - "CreateSupplierRequestTypedDict": ".create_supplier", - "CreateTransferTransactionRequest": ".create_transfer_transaction", - "CreateTransferTransactionRequestTypedDict": ".create_transfer_transaction", - "DeleteCompanyRequest": ".delete_company", - "DeleteCompanyRequestTypedDict": ".delete_company", - "DeleteConnectionRequest": ".delete_connection", - "DeleteConnectionRequestTypedDict": ".delete_connection", - "GetCompanyRequest": ".get_company", - "GetCompanyRequestTypedDict": ".get_company", - "GetCompanyConfigurationRequest": ".get_company_configuration", - "GetCompanyConfigurationRequestTypedDict": ".get_company_configuration", - "GetCompanyInfoRequest": ".get_company_info", - "GetCompanyInfoRequestTypedDict": ".get_company_info", - "GetConnectionRequest": ".get_connection", - "GetConnectionRequestTypedDict": ".get_connection", - "GetCreateBankAccountsModelRequest": ".get_create_bankaccounts_model", - "GetCreateBankAccountsModelRequestTypedDict": ".get_create_bankaccounts_model", - "GetCreateChartOfAccountsModelRequest": ".get_create_chartofaccounts_model", - "GetCreateChartOfAccountsModelRequestTypedDict": ".get_create_chartofaccounts_model", - "GetCustomerRequest": ".get_customer", - "GetCustomerRequestTypedDict": ".get_customer", - "GetDataStatusDataStatuses": ".get_data_status", - "GetDataStatusDataStatusesTypedDict": ".get_data_status", - "GetDataStatusRequest": ".get_data_status", - "GetDataStatusRequestTypedDict": ".get_data_status", - "GetLastSuccessfulSyncRequest": ".get_last_successful_sync", - "GetLastSuccessfulSyncRequestTypedDict": ".get_last_successful_sync", - "GetLatestSyncRequest": ".get_latest_sync", - "GetLatestSyncRequestTypedDict": ".get_latest_sync", - "GetMappingOptionsRequest": ".get_mapping_options", - "GetMappingOptionsRequestTypedDict": ".get_mapping_options", - "GetPullOperationRequest": ".get_pull_operation", - "GetPullOperationRequestTypedDict": ".get_pull_operation", - "GetPushOperationRequest": ".get_push_operation", - "GetPushOperationRequestTypedDict": ".get_push_operation", - "GetSupplierRequest": ".get_supplier", - "GetSupplierRequestTypedDict": ".get_supplier", - "GetSyncByIDRequest": ".get_sync_by_id", - "GetSyncByIDRequestTypedDict": ".get_sync_by_id", - "GetSyncTransactionRequest": ".get_sync_transaction", - "GetSyncTransactionRequestTypedDict": ".get_sync_transaction", - "ListCompaniesRequest": ".list_companies", - "ListCompaniesRequestTypedDict": ".list_companies", - "ListConnectionsRequest": ".list_connections", - "ListConnectionsRequestTypedDict": ".list_connections", - "ListCustomersRequest": ".list_customers", - "ListCustomersRequestTypedDict": ".list_customers", - "ListPullOperationsRequest": ".list_pull_operations", - "ListPullOperationsRequestTypedDict": ".list_pull_operations", - "ListPushOperationsRequest": ".list_push_operations", - "ListPushOperationsRequestTypedDict": ".list_push_operations", - "ListSuppliersRequest": ".list_suppliers", - "ListSuppliersRequestTypedDict": ".list_suppliers", - "ListSyncTransactionsRequest": ".list_sync_transactions", - "ListSyncTransactionsRequestTypedDict": ".list_sync_transactions", - "ListSyncsRequest": ".list_syncs", - "ListSyncsRequestTypedDict": ".list_syncs", - "RefreshAllDataTypesRequest": ".refresh_all_data_types", - "RefreshAllDataTypesRequestTypedDict": ".refresh_all_data_types", - "RefreshDataTypeRequest": ".refresh_data_type", - "RefreshDataTypeRequestTypedDict": ".refresh_data_type", - "ReplaceCompanyRequest": ".replace_company", - "ReplaceCompanyRequestTypedDict": ".replace_company", - "SetCompanyConfigurationRequest": ".set_company_configuration", - "SetCompanyConfigurationRequestTypedDict": ".set_company_configuration", - "UnlinkConnectionRequest": ".unlink_connection", - "UnlinkConnectionRequestTypedDict": ".unlink_connection", - "UnlinkConnectionUpdateConnection": ".unlink_connection", - "UnlinkConnectionUpdateConnectionTypedDict": ".unlink_connection", - "UpdateCompanyRequest": ".update_company", - "UpdateCompanyRequestTypedDict": ".update_company", - "UpdateCustomerRequest": ".update_customer", - "UpdateCustomerRequestTypedDict": ".update_customer", - "UpdateExpenseTransactionRequest": ".update_expense_transaction", - "UpdateExpenseTransactionRequestTypedDict": ".update_expense_transaction", - "UpdateReimbursableExpenseTransactionRequest": ".update_reimbursable_expense_transaction", - "UpdateReimbursableExpenseTransactionRequestTypedDict": ".update_reimbursable_expense_transaction", - "UpdateSupplierRequest": ".update_supplier", - "UpdateSupplierRequestTypedDict": ".update_supplier", - "UploadExpenseAttachmentRequest": ".upload_expense_attachment", - "UploadExpenseAttachmentRequestTypedDict": ".upload_expense_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_expenses.models.shared.adjustmenttransactionrequest import AdjustmentTransactionRequestTypedDict as CreateAdjustmentTransactionAdjustmentTransactionRequestTypedDict +from codat_sync_for_expenses.models.create_connection_request import CreateConnectionRequestTypedDict as CreateConnectionRequestBodyTypedDict +from codat_sync_for_expenses.models.shared.expensetransaction import ExpenseTransactionTypedDict as CreateExpenseTransactionExpenseTransactionTypedDict +from codat_sync_for_expenses.models.shared.reimbursableexpensetransaction import ReimbursableExpenseTransactionTypedDict as CreateReimbursableExpenseTransactionReimbursableExpenseTransactionTypedDict +from codat_sync_for_expenses.models.update_connection import UpdateConnectionTypedDict as UnlinkConnectionUpdateConnectionTypedDict +from codat_sync_for_expenses.models.data_statuses import GetDataStatusDataStatusesTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_account.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_account.py index 028cd4a4b..c12902393 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_account.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_account.py @@ -1,82 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.create_account — re-export of the create_account operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.models.shared import ( - accountprototype as shared_accountprototype, -) -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_expenses.utils import ( - FieldMetadata, - PathParamMetadata, - QueryParamMetadata, - RequestMetadata, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class CreateAccountRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - connection_id: str - r"""Unique identifier for a connection.""" - account_prototype: NotRequired[shared_accountprototype.AccountPrototypeTypedDict] - allow_sync_on_push_complete: NotRequired[bool] - r"""Allow a sync upon push completion.""" - timeout_in_minutes: NotRequired[int] - r"""Time limit for the push operation to complete before it is timed out.""" - - -class CreateAccountRequest(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.""" - - account_prototype: Annotated[ - Optional[shared_accountprototype.AccountPrototype], - FieldMetadata(request=RequestMetadata(media_type="application/json")), - ] = None - - allow_sync_on_push_complete: Annotated[ - Optional[bool], - pydantic.Field(alias="allowSyncOnPushComplete"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = True - r"""Allow a sync upon push completion.""" - - timeout_in_minutes: Annotated[ - Optional[int], - pydantic.Field(alias="timeoutInMinutes"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = None - r"""Time limit for the push operation to complete before it is timed out.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - ["accountPrototype", "allowSyncOnPushComplete", "timeoutInMinutes"] - ) - 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_expenses.api.accounts import CreateAccountRequest +from codat_sync_for_expenses.api.accounts import CreateAccountRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_adjustment_transaction.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_adjustment_transaction.py index 0a7553d80..4a5f25b9c 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_adjustment_transaction.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_adjustment_transaction.py @@ -1,56 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.create_adjustment_transaction — re-export of the create_adjustment_transaction operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.models.shared import ( - adjustmenttransactionrequest as shared_adjustmenttransactionrequest, -) -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_expenses.utils import ( - FieldMetadata, - PathParamMetadata, - RequestMetadata, -) -import pydantic -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class CreateAdjustmentTransactionRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - request_body: NotRequired[ - List[shared_adjustmenttransactionrequest.AdjustmentTransactionRequestTypedDict] - ] - - -class CreateAdjustmentTransactionRequest(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[ - List[shared_adjustmenttransactionrequest.AdjustmentTransactionRequest] - ], - 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_expenses.api.adjustments import CreateAdjustmentTransactionRequest +from codat_sync_for_expenses.api.adjustments import CreateAdjustmentTransactionRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_bank_account.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_bank_account.py index 1ea4d20f9..df06c6d1c 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_bank_account.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_bank_account.py @@ -1,95 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.create_bank_account — re-export of the create_bank_account operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.models.shared import bankaccount as shared_bankaccount -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from codat_sync_for_expenses.utils import ( - FieldMetadata, - PathParamMetadata, - QueryParamMetadata, - 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.""" - bank_account: NotRequired[Nullable[shared_bankaccount.BankAccountTypedDict]] - allow_sync_on_push_complete: NotRequired[bool] - r"""Allow a sync upon push completion.""" - timeout_in_minutes: NotRequired[int] - r"""Time limit for the push operation to complete before it is timed out.""" - - -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.""" - - bank_account: Annotated[ - OptionalNullable[shared_bankaccount.BankAccount], - FieldMetadata(request=RequestMetadata(media_type="application/json")), - ] = UNSET - - allow_sync_on_push_complete: Annotated[ - Optional[bool], - pydantic.Field(alias="allowSyncOnPushComplete"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = True - r"""Allow a sync upon push completion.""" - - timeout_in_minutes: Annotated[ - Optional[int], - pydantic.Field(alias="timeoutInMinutes"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = None - r"""Time limit for the push operation to complete before it is timed out.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - ["BankAccount", "allowSyncOnPushComplete", "timeoutInMinutes"] - ) - nullable_fields = set(["BankAccount"]) - 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 +from codat_sync_for_expenses.api.bank_accounts import CreateBankAccountRequest +from codat_sync_for_expenses.api.bank_accounts import CreateBankAccountRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_connection.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_connection.py index 4ead9d28f..e936c5552 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_connection.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_connection.py @@ -1,81 +1,6 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.create_connection — re-export of the create_connection operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_expenses.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_expenses.api.connections import CreateConnectionRequest +from codat_sync_for_expenses.models.create_connection_request import CreateConnectionRequest as CreateConnectionRequestBody +from codat_sync_for_expenses.models.create_connection_request import CreateConnectionRequestTypedDict as CreateConnectionRequestBodyTypedDict +from codat_sync_for_expenses.api.connections import CreateConnectionRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_customer.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_customer.py index 807825931..1b718e501 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_customer.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_customer.py @@ -1,95 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.create_customer — re-export of the create_customer operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.models.shared import customer as shared_customer -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from codat_sync_for_expenses.utils import ( - FieldMetadata, - PathParamMetadata, - QueryParamMetadata, - RequestMetadata, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class CreateCustomerRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - connection_id: str - r"""Unique identifier for a connection.""" - customer: NotRequired[Nullable[shared_customer.CustomerTypedDict]] - allow_sync_on_push_complete: NotRequired[bool] - r"""Allow a sync upon push completion.""" - timeout_in_minutes: NotRequired[int] - r"""Time limit for the push operation to complete before it is timed out.""" - - -class CreateCustomerRequest(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.""" - - customer: Annotated[ - OptionalNullable[shared_customer.Customer], - FieldMetadata(request=RequestMetadata(media_type="application/json")), - ] = UNSET - - allow_sync_on_push_complete: Annotated[ - Optional[bool], - pydantic.Field(alias="allowSyncOnPushComplete"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = True - r"""Allow a sync upon push completion.""" - - timeout_in_minutes: Annotated[ - Optional[int], - pydantic.Field(alias="timeoutInMinutes"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = None - r"""Time limit for the push operation to complete before it is timed out.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - ["Customer", "allowSyncOnPushComplete", "timeoutInMinutes"] - ) - nullable_fields = set(["Customer"]) - 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 +from codat_sync_for_expenses.api.customers import CreateCustomerRequest +from codat_sync_for_expenses.api.customers import CreateCustomerRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_expense_transaction.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_expense_transaction.py index f9818ed3e..ab9b5fd84 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_expense_transaction.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_expense_transaction.py @@ -1,54 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.create_expense_transaction — re-export of the create_expense_transaction operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.models.shared import ( - expensetransaction as shared_expensetransaction, -) -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_expenses.utils import ( - FieldMetadata, - PathParamMetadata, - RequestMetadata, -) -import pydantic -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class CreateExpenseTransactionRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - request_body: NotRequired[ - List[shared_expensetransaction.ExpenseTransactionTypedDict] - ] - - -class CreateExpenseTransactionRequest(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[List[shared_expensetransaction.ExpenseTransaction]], - 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_expenses.api.expenses import CreateExpenseTransactionRequest +from codat_sync_for_expenses.api.expenses import CreateExpenseTransactionRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_partner_expense_connection.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_partner_expense_connection.py index 17406776b..8be7e3253 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_partner_expense_connection.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_partner_expense_connection.py @@ -1,21 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.create_partner_expense_connection — re-export of the create_partner_expense_connection operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel -from codat_sync_for_expenses.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class CreatePartnerExpenseConnectionRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - - -class CreatePartnerExpenseConnectionRequest(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_expenses.api.connections import CreatePartnerExpenseConnectionRequest +from codat_sync_for_expenses.api.connections import CreatePartnerExpenseConnectionRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_reimbursable_expense_transaction.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_reimbursable_expense_transaction.py index dbef7b5b5..cd812c986 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_reimbursable_expense_transaction.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_reimbursable_expense_transaction.py @@ -1,58 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.create_reimbursable_expense_transaction — re-export of the create_reimbursable_expense_transaction operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.models.shared import ( - reimbursableexpensetransaction as shared_reimbursableexpensetransaction, -) -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_expenses.utils import ( - FieldMetadata, - PathParamMetadata, - RequestMetadata, -) -import pydantic -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class CreateReimbursableExpenseTransactionRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - request_body: NotRequired[ - List[ - shared_reimbursableexpensetransaction.ReimbursableExpenseTransactionTypedDict - ] - ] - - -class CreateReimbursableExpenseTransactionRequest(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[ - List[shared_reimbursableexpensetransaction.ReimbursableExpenseTransaction] - ], - 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_expenses.api.reimbursements import CreateReimbursableExpenseTransactionRequest +from codat_sync_for_expenses.api.reimbursements import CreateReimbursableExpenseTransactionRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_supplier.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_supplier.py index 177c3f241..d7b166433 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_supplier.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_supplier.py @@ -1,95 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.create_supplier — re-export of the create_supplier operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.models.shared import supplier as shared_supplier -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from codat_sync_for_expenses.utils import ( - FieldMetadata, - PathParamMetadata, - QueryParamMetadata, - 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.""" - supplier: NotRequired[Nullable[shared_supplier.SupplierTypedDict]] - allow_sync_on_push_complete: NotRequired[bool] - r"""Allow a sync upon push completion.""" - timeout_in_minutes: NotRequired[int] - r"""Time limit for the push operation to complete before it is timed out.""" - - -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.""" - - supplier: Annotated[ - OptionalNullable[shared_supplier.Supplier], - FieldMetadata(request=RequestMetadata(media_type="application/json")), - ] = UNSET - - allow_sync_on_push_complete: Annotated[ - Optional[bool], - pydantic.Field(alias="allowSyncOnPushComplete"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = True - r"""Allow a sync upon push completion.""" - - timeout_in_minutes: Annotated[ - Optional[int], - pydantic.Field(alias="timeoutInMinutes"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = None - r"""Time limit for the push operation to complete before it is timed out.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - ["Supplier", "allowSyncOnPushComplete", "timeoutInMinutes"] - ) - nullable_fields = set(["Supplier"]) - 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 +from codat_sync_for_expenses.api.suppliers import CreateSupplierRequest +from codat_sync_for_expenses.api.suppliers import CreateSupplierRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_transfer_transaction.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_transfer_transaction.py index d46535aed..61476abe0 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_transfer_transaction.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/create_transfer_transaction.py @@ -1,63 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.create_transfer_transaction — re-export of the create_transfer_transaction operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.models.shared import ( - transfertransactionrequest as shared_transfertransactionrequest, -) -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_expenses.utils import ( - FieldMetadata, - PathParamMetadata, - RequestMetadata, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class CreateTransferTransactionRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - transaction_id: str - r"""The unique identifier for your SMB's transaction.""" - transfer_transaction_request: NotRequired[ - shared_transfertransactionrequest.TransferTransactionRequestTypedDict - ] - - -class CreateTransferTransactionRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - transaction_id: Annotated[ - str, - pydantic.Field(alias="transactionId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""The unique identifier for your SMB's transaction.""" - - transfer_transaction_request: Annotated[ - Optional[shared_transfertransactionrequest.TransferTransactionRequest], - FieldMetadata(request=RequestMetadata(media_type="application/json")), - ] = None - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["TransferTransactionRequest"]) - 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_expenses.api.transfers import CreateTransferTransactionRequest +from codat_sync_for_expenses.api.transfers import CreateTransferTransactionRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/delete_company.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/delete_company.py index f06b15f4f..db2db2224 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/delete_company.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/delete_company.py @@ -1,21 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.delete_company — re-export of the delete_company operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel -from codat_sync_for_expenses.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_expenses.api.companies import DeleteCompanyRequest +from codat_sync_for_expenses.api.companies import DeleteCompanyRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/delete_connection.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/delete_connection.py index 74caa4486..666dc9064 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/delete_connection.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/delete_connection.py @@ -1,30 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.delete_connection — re-export of the delete_connection operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel -from codat_sync_for_expenses.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_expenses.api.connections import DeleteConnectionRequest +from codat_sync_for_expenses.api.connections import DeleteConnectionRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_company.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_company.py index ca429a3bb..535778859 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_company.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_company.py @@ -1,21 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.get_company — re-export of the get_company operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel -from codat_sync_for_expenses.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_expenses.api.companies import GetCompanyRequest +from codat_sync_for_expenses.api.companies import GetCompanyRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_company_configuration.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_company_configuration.py index 4bed062ce..d3e667a31 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_company_configuration.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_company_configuration.py @@ -1,21 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.get_company_configuration — re-export of the get_company_configuration operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel -from codat_sync_for_expenses.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class GetCompanyConfigurationRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - - -class GetCompanyConfigurationRequest(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_expenses.api.configuration import GetCompanyConfigurationRequest +from codat_sync_for_expenses.api.configuration import GetCompanyConfigurationRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_company_info.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_company_info.py index a2fba7c13..ce538d859 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_company_info.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_company_info.py @@ -1,21 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.get_company_info — re-export of the get_company_info operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel -from codat_sync_for_expenses.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class GetCompanyInfoRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - - -class GetCompanyInfoRequest(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_expenses.api.company_info import GetCompanyInfoRequest +from codat_sync_for_expenses.api.company_info import GetCompanyInfoRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_connection.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_connection.py index 5fb7d8a57..188edcb9f 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_connection.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_connection.py @@ -1,30 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.get_connection — re-export of the get_connection operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel -from codat_sync_for_expenses.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_expenses.api.connections import GetConnectionRequest +from codat_sync_for_expenses.api.connections import GetConnectionRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_create_bankaccounts_model.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_create_bankaccounts_model.py index 2cac31c23..9a8202895 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_create_bankaccounts_model.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_create_bankaccounts_model.py @@ -1,30 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.get_create_bankaccounts_model — re-export of the get_create_bankaccounts_model operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel -from codat_sync_for_expenses.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class GetCreateBankAccountsModelRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - connection_id: str - r"""Unique identifier for a connection.""" - - -class GetCreateBankAccountsModelRequest(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_expenses.api.bank_accounts import GetCreateBankAccountsModelRequest +from codat_sync_for_expenses.api.bank_accounts import GetCreateBankAccountsModelRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_create_chartofaccounts_model.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_create_chartofaccounts_model.py index a34eec985..f77aeb0eb 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_create_chartofaccounts_model.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_create_chartofaccounts_model.py @@ -1,30 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.get_create_chartofaccounts_model — re-export of the get_create_chartofaccounts_model operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel -from codat_sync_for_expenses.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class GetCreateChartOfAccountsModelRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - connection_id: str - r"""Unique identifier for a connection.""" - - -class GetCreateChartOfAccountsModelRequest(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_expenses.api.accounts import GetCreateChartOfAccountsModelRequest +from codat_sync_for_expenses.api.accounts import GetCreateChartOfAccountsModelRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_customer.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_customer.py index a2a9c4ac4..cb22e7488 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_customer.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_customer.py @@ -1,30 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.get_customer — re-export of the get_customer operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel -from codat_sync_for_expenses.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class GetCustomerRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - customer_id: str - r"""Unique identifier for a customer.""" - - -class GetCustomerRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - customer_id: Annotated[ - str, - pydantic.Field(alias="customerId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a customer.""" +from codat_sync_for_expenses.api.customers import GetCustomerRequest +from codat_sync_for_expenses.api.customers import GetCustomerRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_data_status.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_data_status.py index 163048b2d..5a9f17a77 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_data_status.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_data_status.py @@ -1,400 +1,6 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.get_data_status — re-export of the get_data_status operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.models.shared import datastatus as shared_datastatus -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_expenses.utils import FieldMetadata, PathParamMetadata -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class GetDataStatusRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - - -class GetDataStatusRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - -class GetDataStatusDataStatusesTypedDict(TypedDict): - r"""OK""" - - account_transactions: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - balance_sheet: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - bank_accounts: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - bank_transactions: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - banking_account_balances: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - banking_accounts: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - banking_transaction_categories: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - banking_transactions: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - bill_credit_notes: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - bill_payments: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - bills: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - cash_flow_statement: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - chart_of_accounts: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - commerce_company_info: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - commerce_customers: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - commerce_disputes: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - commerce_locations: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - commerce_orders: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - commerce_payment_methods: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - commerce_payments: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - commerce_product_categories: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - commerce_products: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - commerce_tax_components: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - commerce_transactions: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - company: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - credit_notes: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - customers: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - direct_costs: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - direct_incomes: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - invoices: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - item_receipts: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - items: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - journal_entries: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - journals: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - payment_methods: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - payments: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - profit_and_loss: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - purchase_orders: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - sales_orders: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - suppliers: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - tax_rates: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - tracking_categories: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - transfers: NotRequired[shared_datastatus.DataStatusTypedDict] - r"""Describes the state of data in the Codat cache for a company and data type""" - - -class GetDataStatusDataStatuses(BaseModel): - r"""OK""" - - account_transactions: Annotated[ - Optional[shared_datastatus.DataStatus], - pydantic.Field(alias="accountTransactions"), - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - balance_sheet: Annotated[ - Optional[shared_datastatus.DataStatus], pydantic.Field(alias="balanceSheet") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - bank_accounts: Annotated[ - Optional[shared_datastatus.DataStatus], pydantic.Field(alias="bankAccounts") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - bank_transactions: Annotated[ - Optional[shared_datastatus.DataStatus], pydantic.Field(alias="bankTransactions") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - banking_account_balances: Annotated[ - Optional[shared_datastatus.DataStatus], - pydantic.Field(alias="banking-accountBalances"), - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - banking_accounts: Annotated[ - Optional[shared_datastatus.DataStatus], pydantic.Field(alias="banking-accounts") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - banking_transaction_categories: Annotated[ - Optional[shared_datastatus.DataStatus], - pydantic.Field(alias="banking-transactionCategories"), - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - banking_transactions: Annotated[ - Optional[shared_datastatus.DataStatus], - pydantic.Field(alias="banking-transactions"), - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - bill_credit_notes: Annotated[ - Optional[shared_datastatus.DataStatus], pydantic.Field(alias="billCreditNotes") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - bill_payments: Annotated[ - Optional[shared_datastatus.DataStatus], pydantic.Field(alias="billPayments") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - bills: Optional[shared_datastatus.DataStatus] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - cash_flow_statement: Annotated[ - Optional[shared_datastatus.DataStatus], - pydantic.Field(alias="cashFlowStatement"), - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - chart_of_accounts: Annotated[ - Optional[shared_datastatus.DataStatus], pydantic.Field(alias="chartOfAccounts") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - commerce_company_info: Annotated[ - Optional[shared_datastatus.DataStatus], - pydantic.Field(alias="commerce-companyInfo"), - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - commerce_customers: Annotated[ - Optional[shared_datastatus.DataStatus], - pydantic.Field(alias="commerce-customers"), - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - commerce_disputes: Annotated[ - Optional[shared_datastatus.DataStatus], - pydantic.Field(alias="commerce-disputes"), - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - commerce_locations: Annotated[ - Optional[shared_datastatus.DataStatus], - pydantic.Field(alias="commerce-locations"), - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - commerce_orders: Annotated[ - Optional[shared_datastatus.DataStatus], pydantic.Field(alias="commerce-orders") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - commerce_payment_methods: Annotated[ - Optional[shared_datastatus.DataStatus], - pydantic.Field(alias="commerce-paymentMethods"), - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - commerce_payments: Annotated[ - Optional[shared_datastatus.DataStatus], - pydantic.Field(alias="commerce-payments"), - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - commerce_product_categories: Annotated[ - Optional[shared_datastatus.DataStatus], - pydantic.Field(alias="commerce-productCategories"), - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - commerce_products: Annotated[ - Optional[shared_datastatus.DataStatus], - pydantic.Field(alias="commerce-products"), - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - commerce_tax_components: Annotated[ - Optional[shared_datastatus.DataStatus], - pydantic.Field(alias="commerce-taxComponents"), - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - commerce_transactions: Annotated[ - Optional[shared_datastatus.DataStatus], - pydantic.Field(alias="commerce-transactions"), - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - company: Optional[shared_datastatus.DataStatus] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - credit_notes: Annotated[ - Optional[shared_datastatus.DataStatus], pydantic.Field(alias="creditNotes") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - customers: Optional[shared_datastatus.DataStatus] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - direct_costs: Annotated[ - Optional[shared_datastatus.DataStatus], pydantic.Field(alias="directCosts") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - direct_incomes: Annotated[ - Optional[shared_datastatus.DataStatus], pydantic.Field(alias="directIncomes") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - invoices: Optional[shared_datastatus.DataStatus] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - item_receipts: Annotated[ - Optional[shared_datastatus.DataStatus], pydantic.Field(alias="itemReceipts") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - items: Optional[shared_datastatus.DataStatus] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - journal_entries: Annotated[ - Optional[shared_datastatus.DataStatus], pydantic.Field(alias="journalEntries") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - journals: Optional[shared_datastatus.DataStatus] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - payment_methods: Annotated[ - Optional[shared_datastatus.DataStatus], pydantic.Field(alias="paymentMethods") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - payments: Optional[shared_datastatus.DataStatus] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - profit_and_loss: Annotated[ - Optional[shared_datastatus.DataStatus], pydantic.Field(alias="profitAndLoss") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - purchase_orders: Annotated[ - Optional[shared_datastatus.DataStatus], pydantic.Field(alias="purchaseOrders") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - sales_orders: Annotated[ - Optional[shared_datastatus.DataStatus], pydantic.Field(alias="salesOrders") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - suppliers: Optional[shared_datastatus.DataStatus] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - tax_rates: Annotated[ - Optional[shared_datastatus.DataStatus], pydantic.Field(alias="taxRates") - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - tracking_categories: Annotated[ - Optional[shared_datastatus.DataStatus], - pydantic.Field(alias="trackingCategories"), - ] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - transfers: Optional[shared_datastatus.DataStatus] = None - r"""Describes the state of data in the Codat cache for a company and data type""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "accountTransactions", - "balanceSheet", - "bankAccounts", - "bankTransactions", - "banking-accountBalances", - "banking-accounts", - "banking-transactionCategories", - "banking-transactions", - "billCreditNotes", - "billPayments", - "bills", - "cashFlowStatement", - "chartOfAccounts", - "commerce-companyInfo", - "commerce-customers", - "commerce-disputes", - "commerce-locations", - "commerce-orders", - "commerce-paymentMethods", - "commerce-payments", - "commerce-productCategories", - "commerce-products", - "commerce-taxComponents", - "commerce-transactions", - "company", - "creditNotes", - "customers", - "directCosts", - "directIncomes", - "invoices", - "itemReceipts", - "items", - "journalEntries", - "journals", - "paymentMethods", - "payments", - "profitAndLoss", - "purchaseOrders", - "salesOrders", - "suppliers", - "taxRates", - "trackingCategories", - "transfers", - ] - ) - 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: - GetDataStatusDataStatuses.model_rebuild() -except NameError: - pass +from codat_sync_for_expenses.models.data_statuses import GetDataStatusDataStatuses +from codat_sync_for_expenses.models.data_statuses import GetDataStatusDataStatusesTypedDict +from codat_sync_for_expenses.api.manage_data import GetDataStatusRequest +from codat_sync_for_expenses.api.manage_data import GetDataStatusRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_last_successful_sync.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_last_successful_sync.py index 77151a2dd..63eda3ee9 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_last_successful_sync.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_last_successful_sync.py @@ -1,21 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.get_last_successful_sync — re-export of the get_last_successful_sync operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel -from codat_sync_for_expenses.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class GetLastSuccessfulSyncRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - - -class GetLastSuccessfulSyncRequest(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_expenses.api.sync import GetLastSuccessfulSyncRequest +from codat_sync_for_expenses.api.sync import GetLastSuccessfulSyncRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_latest_sync.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_latest_sync.py index 6263a106d..6f5851053 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_latest_sync.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_latest_sync.py @@ -1,21 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.get_latest_sync — re-export of the get_latest_sync operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel -from codat_sync_for_expenses.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class GetLatestSyncRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - - -class GetLatestSyncRequest(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_expenses.api.sync import GetLatestSyncRequest +from codat_sync_for_expenses.api.sync import GetLatestSyncRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_mapping_options.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_mapping_options.py index b7cebbe88..b4843179f 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_mapping_options.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_mapping_options.py @@ -1,21 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.get_mapping_options — re-export of the get_mapping_options operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel -from codat_sync_for_expenses.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class GetMappingOptionsRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - - -class GetMappingOptionsRequest(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_expenses.api.mapping_options import GetMappingOptionsRequest +from codat_sync_for_expenses.api.mapping_options import GetMappingOptionsRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_pull_operation.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_pull_operation.py index dec74b03b..5548639b1 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_pull_operation.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_pull_operation.py @@ -1,30 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.get_pull_operation — re-export of the get_pull_operation operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel -from codat_sync_for_expenses.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class GetPullOperationRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - dataset_id: str - r"""Unique identifier for the dataset that completed its sync.""" - - -class GetPullOperationRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - dataset_id: Annotated[ - str, - pydantic.Field(alias="datasetId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for the dataset that completed its sync.""" +from codat_sync_for_expenses.api.manage_data import GetPullOperationRequest +from codat_sync_for_expenses.api.manage_data import GetPullOperationRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_push_operation.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_push_operation.py index cccda80a3..ca1b3834b 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_push_operation.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_push_operation.py @@ -1,30 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.get_push_operation — re-export of the get_push_operation operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel -from codat_sync_for_expenses.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class GetPushOperationRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - push_operation_key: str - r"""Push operation key.""" - - -class GetPushOperationRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - push_operation_key: Annotated[ - str, - pydantic.Field(alias="pushOperationKey"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Push operation key.""" +from codat_sync_for_expenses.api.push_operations import GetPushOperationRequest +from codat_sync_for_expenses.api.push_operations import GetPushOperationRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_supplier.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_supplier.py index 769ac5ae0..6a2b5447d 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_supplier.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_supplier.py @@ -1,30 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.get_supplier — re-export of the get_supplier operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel -from codat_sync_for_expenses.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class GetSupplierRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - supplier_id: str - r"""Unique identifier for a supplier.""" - - -class GetSupplierRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - supplier_id: Annotated[ - str, - pydantic.Field(alias="supplierId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a supplier.""" +from codat_sync_for_expenses.api.suppliers import GetSupplierRequest +from codat_sync_for_expenses.api.suppliers import GetSupplierRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_sync_by_id.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_sync_by_id.py index 7315d40eb..d01d36de8 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_sync_by_id.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_sync_by_id.py @@ -1,30 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.get_sync_by_id — re-export of the get_sync_by_id operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel -from codat_sync_for_expenses.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class GetSyncByIDRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - sync_id: str - r"""Unique identifier for a sync.""" - - -class GetSyncByIDRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - sync_id: Annotated[ - str, - pydantic.Field(alias="syncId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a sync.""" +from codat_sync_for_expenses.api.sync import GetSyncByIDRequest +from codat_sync_for_expenses.api.sync import GetSyncByIDRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_sync_transaction.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_sync_transaction.py index ee22b2b87..4786d6a66 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_sync_transaction.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/get_sync_transaction.py @@ -1,39 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.get_sync_transaction — re-export of the get_sync_transaction operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel -from codat_sync_for_expenses.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class GetSyncTransactionRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - sync_id: str - r"""Unique identifier for a sync.""" - transaction_id: str - r"""The unique identifier for your SMB's transaction.""" - - -class GetSyncTransactionRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - sync_id: Annotated[ - str, - pydantic.Field(alias="syncId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a sync.""" - - transaction_id: Annotated[ - str, - pydantic.Field(alias="transactionId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""The unique identifier for your SMB's transaction.""" +from codat_sync_for_expenses.api.transaction_status import GetSyncTransactionRequest +from codat_sync_for_expenses.api.transaction_status import GetSyncTransactionRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/list_companies.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/list_companies.py index 7b2002175..071932249 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/list_companies.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/list_companies.py @@ -1,72 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.list_companies — re-export of the list_companies operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_expenses.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): - order_by: NotRequired[str] - r"""Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).""" - 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).""" - 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): - 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).""" - - 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).""" - - 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(["orderBy", "page", "pageSize", "query", "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_expenses.api.companies import ListCompaniesRequest +from codat_sync_for_expenses.api.companies import ListCompaniesRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/list_connections.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/list_connections.py index f16a8075c..9375a961b 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/list_connections.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/list_connections.py @@ -1,77 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.list_connections — re-export of the list_connections operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_expenses.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.""" - order_by: NotRequired[str] - r"""Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).""" - 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).""" - - -class ListConnectionsRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - 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).""" - - 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).""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["orderBy", "page", "pageSize", "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_expenses.api.connections import ListConnectionsRequest +from codat_sync_for_expenses.api.connections import ListConnectionsRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/list_customers.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/list_customers.py index b2dc0899c..45ec52066 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/list_customers.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/list_customers.py @@ -1,77 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.list_customers — re-export of the list_customers operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_expenses.utils import ( - FieldMetadata, - PathParamMetadata, - QueryParamMetadata, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class ListCustomersRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - order_by: NotRequired[str] - r"""Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).""" - 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).""" - - -class ListCustomersRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - 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).""" - - 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).""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["orderBy", "page", "pageSize", "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_expenses.api.customers import ListCustomersRequest +from codat_sync_for_expenses.api.customers import ListCustomersRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/list_pull_operations.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/list_pull_operations.py index 1c9be3ef8..a10413978 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/list_pull_operations.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/list_pull_operations.py @@ -1,77 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.list_pull_operations — re-export of the list_pull_operations operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_expenses.utils import ( - FieldMetadata, - PathParamMetadata, - QueryParamMetadata, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class ListPullOperationsRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - order_by: NotRequired[str] - r"""Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).""" - 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).""" - - -class ListPullOperationsRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - 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).""" - - 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).""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["orderBy", "page", "pageSize", "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_expenses.api.manage_data import ListPullOperationsRequest +from codat_sync_for_expenses.api.manage_data import ListPullOperationsRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/list_push_operations.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/list_push_operations.py index eba8996a4..04469c6f0 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/list_push_operations.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/list_push_operations.py @@ -1,77 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.list_push_operations — re-export of the list_push_operations operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_expenses.utils import ( - FieldMetadata, - PathParamMetadata, - QueryParamMetadata, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class ListPushOperationsRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - order_by: NotRequired[str] - r"""Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).""" - 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).""" - - -class ListPushOperationsRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - 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).""" - - 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).""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["orderBy", "page", "pageSize", "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_expenses.api.push_operations import ListPushOperationsRequest +from codat_sync_for_expenses.api.push_operations import ListPushOperationsRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/list_suppliers.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/list_suppliers.py index 4410053b6..a5169a3d4 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/list_suppliers.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/list_suppliers.py @@ -1,77 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.list_suppliers — re-export of the list_suppliers operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_expenses.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.""" - order_by: NotRequired[str] - r"""Field to order results by. [Read more](https://docs.codat.io/using-the-api/ordering-results).""" - 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).""" - - -class ListSuppliersRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - 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).""" - - 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).""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["orderBy", "page", "pageSize", "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_expenses.api.suppliers import ListSuppliersRequest +from codat_sync_for_expenses.api.suppliers import ListSuppliersRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/list_sync_transactions.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/list_sync_transactions.py index f7243e1bc..002689aa7 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/list_sync_transactions.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/list_sync_transactions.py @@ -1,69 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.list_sync_transactions — re-export of the list_sync_transactions operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_expenses.utils import ( - FieldMetadata, - PathParamMetadata, - QueryParamMetadata, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class ListSyncTransactionsRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - sync_id: str - r"""Unique identifier for a sync.""" - 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).""" - - -class ListSyncTransactionsRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - sync_id: Annotated[ - str, - pydantic.Field(alias="syncId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a sync.""" - - 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).""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["page", "pageSize"]) - 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_expenses.api.transaction_status import ListSyncTransactionsRequest +from codat_sync_for_expenses.api.transaction_status import ListSyncTransactionsRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/list_syncs.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/list_syncs.py index 90658a7a7..500a3b91a 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/list_syncs.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/list_syncs.py @@ -1,21 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.list_syncs — re-export of the list_syncs operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel -from codat_sync_for_expenses.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class ListSyncsRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - - -class ListSyncsRequest(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_expenses.api.sync import ListSyncsRequest +from codat_sync_for_expenses.api.sync import ListSyncsRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/refresh_all_data_types.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/refresh_all_data_types.py index 4fb422130..8efd2c9a6 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/refresh_all_data_types.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/refresh_all_data_types.py @@ -1,21 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.refresh_all_data_types — re-export of the refresh_all_data_types operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel -from codat_sync_for_expenses.utils import FieldMetadata, PathParamMetadata -import pydantic -from typing_extensions import Annotated, TypedDict - - -class RefreshAllDataTypesRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - - -class RefreshAllDataTypesRequest(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_expenses.api.manage_data import RefreshAllDataTypesRequest +from codat_sync_for_expenses.api.manage_data import RefreshAllDataTypesRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/refresh_data_type.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/refresh_data_type.py index fa54b12ac..54971fd15 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/refresh_data_type.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/refresh_data_type.py @@ -1,64 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.refresh_data_type — re-export of the refresh_data_type operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.models.shared import ( - schema_datatype as shared_schema_datatype, -) -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_expenses.utils import ( - FieldMetadata, - PathParamMetadata, - QueryParamMetadata, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class RefreshDataTypeRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - data_type: shared_schema_datatype.SchemaDataType - r"""The key of a Codat data type""" - connection_id: NotRequired[str] - r"""Optionally, provide a data connection id to only queue pull operations on that connection.""" - - -class RefreshDataTypeRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - data_type: Annotated[ - shared_schema_datatype.SchemaDataType, - pydantic.Field(alias="dataType"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""The key of a Codat data type""" - - connection_id: Annotated[ - Optional[str], - pydantic.Field(alias="connectionId"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = None - r"""Optionally, provide a data connection id to only queue pull operations on that connection.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["connectionId"]) - 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_expenses.api.manage_data import RefreshDataTypeRequest +from codat_sync_for_expenses.api.manage_data import RefreshDataTypeRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/replace_company.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/replace_company.py index 4447d192d..0d643fb20 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/replace_company.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/replace_company.py @@ -1,54 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.replace_company — re-export of the replace_company operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.models.shared import ( - companyrequestbody as shared_companyrequestbody, -) -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_expenses.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_expenses.api.companies import ReplaceCompanyRequest +from codat_sync_for_expenses.api.companies import ReplaceCompanyRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/set_company_configuration.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/set_company_configuration.py index 3ec9a49c7..79681fa74 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/set_company_configuration.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/set_company_configuration.py @@ -1,54 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.set_company_configuration — re-export of the set_company_configuration operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.models.shared import ( - companyconfiguration as shared_companyconfiguration, -) -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_expenses.utils import ( - FieldMetadata, - PathParamMetadata, - RequestMetadata, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class SetCompanyConfigurationRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - company_configuration: NotRequired[ - shared_companyconfiguration.CompanyConfigurationTypedDict - ] - - -class SetCompanyConfigurationRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - company_configuration: Annotated[ - Optional[shared_companyconfiguration.CompanyConfiguration], - FieldMetadata(request=RequestMetadata(media_type="application/json")), - ] = None - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["CompanyConfiguration"]) - 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_expenses.api.configuration import SetCompanyConfigurationRequest +from codat_sync_for_expenses.api.configuration import SetCompanyConfigurationRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/unlink_connection.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/unlink_connection.py index ad4b5ab95..46bf04a2a 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/unlink_connection.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/unlink_connection.py @@ -1,87 +1,6 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.unlink_connection — re-export of the unlink_connection operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.models.shared import ( - dataconnectionstatus as shared_dataconnectionstatus, -) -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_expenses.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_expenses.api.connections import UnlinkConnectionRequest +from codat_sync_for_expenses.api.connections import UnlinkConnectionRequestTypedDict +from codat_sync_for_expenses.models.update_connection import UpdateConnection as UnlinkConnectionUpdateConnection +from codat_sync_for_expenses.models.update_connection import UpdateConnectionTypedDict as UnlinkConnectionUpdateConnectionTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/update_company.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/update_company.py index 16147f3a4..8c5858a44 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/update_company.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/update_company.py @@ -1,54 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.update_company — re-export of the update_company operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.models.shared import ( - companyupdaterequest as shared_companyupdaterequest, -) -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_expenses.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_expenses.api.companies import UpdateCompanyRequest +from codat_sync_for_expenses.api.companies import UpdateCompanyRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/update_customer.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/update_customer.py index db51e3c3b..c14d562a0 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/update_customer.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/update_customer.py @@ -1,113 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.update_customer — re-export of the update_customer operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.models.shared import customer as shared_customer -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from codat_sync_for_expenses.utils import ( - FieldMetadata, - PathParamMetadata, - QueryParamMetadata, - RequestMetadata, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class UpdateCustomerRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - connection_id: str - r"""Unique identifier for a connection.""" - customer_id: str - r"""Unique identifier for a customer.""" - customer: NotRequired[Nullable[shared_customer.CustomerTypedDict]] - allow_sync_on_push_complete: NotRequired[bool] - r"""Allow a sync upon push completion.""" - force_update: NotRequired[bool] - r"""When updating data in the destination platform Codat checks the `sourceModifiedDate` against the `lastupdated` date from the accounting software, if they're different Codat will return an error suggesting you should initiate another pull of the data. If this is set to `true` then the update will override this check.""" - timeout_in_minutes: NotRequired[int] - r"""Time limit for the push operation to complete before it is timed out.""" - - -class UpdateCustomerRequest(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.""" - - customer_id: Annotated[ - str, - pydantic.Field(alias="customerId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a customer.""" - - customer: Annotated[ - OptionalNullable[shared_customer.Customer], - FieldMetadata(request=RequestMetadata(media_type="application/json")), - ] = UNSET - - allow_sync_on_push_complete: Annotated[ - Optional[bool], - pydantic.Field(alias="allowSyncOnPushComplete"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = True - r"""Allow a sync upon push completion.""" - - force_update: Annotated[ - Optional[bool], - pydantic.Field(alias="forceUpdate"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = False - r"""When updating data in the destination platform Codat checks the `sourceModifiedDate` against the `lastupdated` date from the accounting software, if they're different Codat will return an error suggesting you should initiate another pull of the data. If this is set to `true` then the update will override this check.""" - - timeout_in_minutes: Annotated[ - Optional[int], - pydantic.Field(alias="timeoutInMinutes"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = None - r"""Time limit for the push operation to complete before it is timed out.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - ["Customer", "allowSyncOnPushComplete", "forceUpdate", "timeoutInMinutes"] - ) - nullable_fields = set(["Customer"]) - 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 +from codat_sync_for_expenses.api.customers import UpdateCustomerRequest +from codat_sync_for_expenses.api.customers import UpdateCustomerRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/update_expense_transaction.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/update_expense_transaction.py index f05607adf..031bca97c 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/update_expense_transaction.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/update_expense_transaction.py @@ -1,63 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.update_expense_transaction — re-export of the update_expense_transaction operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.models.shared import ( - updateexpenserequest as shared_updateexpenserequest, -) -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_expenses.utils import ( - FieldMetadata, - PathParamMetadata, - RequestMetadata, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class UpdateExpenseTransactionRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - transaction_id: str - r"""The unique identifier for your SMB's transaction.""" - update_expense_request: NotRequired[ - shared_updateexpenserequest.UpdateExpenseRequestTypedDict - ] - - -class UpdateExpenseTransactionRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - transaction_id: Annotated[ - str, - pydantic.Field(alias="transactionId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""The unique identifier for your SMB's transaction.""" - - update_expense_request: Annotated[ - Optional[shared_updateexpenserequest.UpdateExpenseRequest], - FieldMetadata(request=RequestMetadata(media_type="application/json")), - ] = None - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["UpdateExpenseRequest"]) - 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_expenses.api.expenses import UpdateExpenseTransactionRequest +from codat_sync_for_expenses.api.expenses import UpdateExpenseTransactionRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/update_reimbursable_expense_transaction.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/update_reimbursable_expense_transaction.py index ab40af082..2bc6745e1 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/update_reimbursable_expense_transaction.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/update_reimbursable_expense_transaction.py @@ -1,65 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.update_reimbursable_expense_transaction — re-export of the update_reimbursable_expense_transaction operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.models.shared import ( - updatereimbursableexpensetransactionrequest as shared_updatereimbursableexpensetransactionrequest, -) -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_expenses.utils import ( - FieldMetadata, - PathParamMetadata, - RequestMetadata, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class UpdateReimbursableExpenseTransactionRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - transaction_id: str - r"""The unique identifier for your SMB's transaction.""" - update_reimbursable_expense_transaction_request: NotRequired[ - shared_updatereimbursableexpensetransactionrequest.UpdateReimbursableExpenseTransactionRequestTypedDict - ] - - -class UpdateReimbursableExpenseTransactionRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - transaction_id: Annotated[ - str, - pydantic.Field(alias="transactionId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""The unique identifier for your SMB's transaction.""" - - update_reimbursable_expense_transaction_request: Annotated[ - Optional[ - shared_updatereimbursableexpensetransactionrequest.UpdateReimbursableExpenseTransactionRequest - ], - FieldMetadata(request=RequestMetadata(media_type="application/json")), - ] = None - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["UpdateReimbursableExpenseTransactionRequest"]) - 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_expenses.api.reimbursements import UpdateReimbursableExpenseTransactionRequest +from codat_sync_for_expenses.api.reimbursements import UpdateReimbursableExpenseTransactionRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/update_supplier.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/update_supplier.py index 8d033bded..612ff0c6c 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/update_supplier.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/update_supplier.py @@ -1,113 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.update_supplier — re-export of the update_supplier operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.models.shared import supplier as shared_supplier -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from codat_sync_for_expenses.utils import ( - FieldMetadata, - PathParamMetadata, - QueryParamMetadata, - 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: NotRequired[Nullable[shared_supplier.SupplierTypedDict]] - allow_sync_on_push_complete: NotRequired[bool] - r"""Allow a sync upon push completion.""" - force_update: NotRequired[bool] - r"""When updating data in the destination platform Codat checks the `sourceModifiedDate` against the `lastupdated` date from the accounting software, if they're different Codat will return an error suggesting you should initiate another pull of the data. If this is set to `true` then the update will override this check.""" - timeout_in_minutes: NotRequired[int] - r"""Time limit for the push operation to complete before it is timed out.""" - - -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: Annotated[ - OptionalNullable[shared_supplier.Supplier], - FieldMetadata(request=RequestMetadata(media_type="application/json")), - ] = UNSET - - allow_sync_on_push_complete: Annotated[ - Optional[bool], - pydantic.Field(alias="allowSyncOnPushComplete"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = True - r"""Allow a sync upon push completion.""" - - force_update: Annotated[ - Optional[bool], - pydantic.Field(alias="forceUpdate"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = False - r"""When updating data in the destination platform Codat checks the `sourceModifiedDate` against the `lastupdated` date from the accounting software, if they're different Codat will return an error suggesting you should initiate another pull of the data. If this is set to `true` then the update will override this check.""" - - timeout_in_minutes: Annotated[ - Optional[int], - pydantic.Field(alias="timeoutInMinutes"), - FieldMetadata(query=QueryParamMetadata(style="form", explode=True)), - ] = None - r"""Time limit for the push operation to complete before it is timed out.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - ["Supplier", "allowSyncOnPushComplete", "forceUpdate", "timeoutInMinutes"] - ) - nullable_fields = set(["Supplier"]) - 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 +from codat_sync_for_expenses.api.suppliers import UpdateSupplierRequest +from codat_sync_for_expenses.api.suppliers import UpdateSupplierRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/upload_expense_attachment.py b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/upload_expense_attachment.py index 9ff9c63bf..fa451a4a7 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/operations/upload_expense_attachment.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/operations/upload_expense_attachment.py @@ -1,70 +1,4 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.operations.upload_expense_attachment — re-export of the upload_expense_attachment operation envelope.""" -from __future__ import annotations -from codat_sync_for_expenses.models.shared import ( - attachmentupload as shared_attachmentupload, -) -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_expenses.utils import ( - FieldMetadata, - PathParamMetadata, - RequestMetadata, -) -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class UploadExpenseAttachmentRequestTypedDict(TypedDict): - company_id: str - r"""Unique identifier for a company.""" - sync_id: str - r"""Unique identifier for a sync.""" - transaction_id: str - r"""The unique identifier for your SMB's transaction.""" - attachment_upload: NotRequired[shared_attachmentupload.AttachmentUploadTypedDict] - - -class UploadExpenseAttachmentRequest(BaseModel): - company_id: Annotated[ - str, - pydantic.Field(alias="companyId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a company.""" - - sync_id: Annotated[ - str, - pydantic.Field(alias="syncId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""Unique identifier for a sync.""" - - transaction_id: Annotated[ - str, - pydantic.Field(alias="transactionId"), - FieldMetadata(path=PathParamMetadata(style="simple", explode=False)), - ] - r"""The unique identifier for your SMB's transaction.""" - - 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_expenses.api.attachments import UploadExpenseAttachmentRequest +from codat_sync_for_expenses.api.attachments import UploadExpenseAttachmentRequestTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/paging_info.py b/sync-for-expenses/src/codat_sync_for_expenses/models/paging_info.py new file mode 100644 index 000000000..14e164ec6 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/paging_info.py @@ -0,0 +1,113 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.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-expenses/src/codat_sync_for_expenses/models/phone_number_items_type.py b/sync-for-expenses/src/codat_sync_for_expenses/models/phone_number_items_type.py new file mode 100644 index 000000000..cb092c82a --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/phone_number_items_type.py @@ -0,0 +1,12 @@ +from __future__ import annotations + +from enum import Enum + + +class PhoneNumberItemsType(str, Enum): + """PhoneNumberItemsType enum (lifted from inline OAS enum).""" + PRIMARY = 'Primary' + LANDLINE = 'Landline' + MOBILE = 'Mobile' + FAX = 'Fax' + UNKNOWN = 'Unknown' diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/__init__.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/__init__.py index 2585206d7..86812f7c2 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/__init__.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/__init__.py @@ -1,767 +1,619 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.models.shared — domain-shared models.""" -from typing import Any, TYPE_CHECKING - -from codat_sync_for_expenses.utils.dynamic_imports import lazy_getattr, lazy_dir +from importlib import import_module +from typing import TYPE_CHECKING if TYPE_CHECKING: - from .accountingaddresstype import AccountingAddressType - from .accountmappinginfo import ( - AccountMappingInfo, - AccountMappingInfoAccountType, - AccountMappingInfoTypedDict, - ) - from .accountprototype import ( - AccountPrototype, - AccountPrototypeTypedDict, - ValidDataTypeLinks, - ValidDataTypeLinksTypedDict, - ) - from .accountstatus import AccountStatus - from .accounttype import AccountType - from .adjustmenttransactionline import ( - AdjustmentTransactionLine, - AdjustmentTransactionLineTypedDict, - ) - from .adjustmenttransactionrequest import ( - AdjustmentTransactionRequest, - AdjustmentTransactionRequestTypedDict, - ) - from .adjustmenttransactionresponse import ( - AdjustmentTransactionResponse, - AdjustmentTransactionResponseTypedDict, - ) - from .apaccountref import ApAccountRef, ApAccountRefTypedDict - from .attachment import Attachment, AttachmentTypedDict - from .attachmentupload import AttachmentUpload, AttachmentUploadTypedDict - from .bankaccount import BankAccount, BankAccountType, BankAccountTypedDict - from .bankaccountdetails import BankAccountDetails, BankAccountDetailsTypedDict - from .bankaccountstatus import BankAccountStatus - from .clientratelimitwebhook import ( - ClientRateLimitWebhook, - ClientRateLimitWebhookTypedDict, - ) - from .clientratelimitwebhookpayload import ( - ClientRateLimitWebhookPayload, - ClientRateLimitWebhookPayloadTypedDict, - ) - from .codatfile import CodatFile, CodatFileTypedDict - from .companies import Companies, CompaniesTypedDict - from .company import Company, CompanyTypedDict - from .companyconfiguration import ( - CompanyConfiguration, - CompanyConfigurationTypedDict, - ) - from .companyinformation import ( - AccountingAddress, - AccountingAddressTypedDict, - CompanyInformation, - CompanyInformationSchemasType, - CompanyInformationType, - CompanyInformationTypedDict, - Phone, - PhoneTypedDict, - Weblink, - WeblinkTypedDict, - ) - from .companyreference import ( - CompanyReference, - CompanyReferenceLinks, - CompanyReferenceLinksTypedDict, - CompanyReferenceTypedDict, - ) - from .companyrequestbody import CompanyRequestBody, CompanyRequestBodyTypedDict - from .companysyncstatus import CompanySyncStatus, CompanySyncStatusTypedDict - from .companyupdaterequest import ( - CompanyUpdateRequest, - CompanyUpdateRequestTypedDict, - ) - from .connection import Connection, ConnectionTypedDict, SourceType - from .connections import Connections, ConnectionsTypedDict - from .contact import Contact, ContactTypedDict - from .createaccountresponse import ( - AccountingAccount, - AccountingAccountTypedDict, - CreateAccountResponse, - CreateAccountResponseMetadata, - CreateAccountResponseMetadataTypedDict, - CreateAccountResponseTypedDict, - CreateAccountResponseValidDataTypeLinks, - CreateAccountResponseValidDataTypeLinksTypedDict, - ) - from .createbankaccountresponse import ( - AccountingBankAccount, - AccountingBankAccountTypedDict, - CreateBankAccountResponse, - CreateBankAccountResponseBankAccountType, - CreateBankAccountResponseTypedDict, - ) - from .createcustomerresponse import ( - AccountingCustomer, - AccountingCustomerTypedDict, - CreateCustomerResponse, - CreateCustomerResponseTypedDict, - ) - from .createexpenseresponse import ( - CreateExpenseResponse, - CreateExpenseResponseTypedDict, - ) - from .createreimbursableexpenseresponse import ( - CreateReimbursableExpenseResponse, - CreateReimbursableExpenseResponseTypedDict, - ) - from .createsupplierresponse import ( - AccountingSupplier, - AccountingSupplierTypedDict, - CreateSupplierResponse, - CreateSupplierResponseTypedDict, - ) - from .customer import Customer, CustomerTypedDict - from .customerdetails import CustomerDetails, CustomerDetailsTypedDict - from .customers import Customers, CustomersTypedDict - from .customerstatus import CustomerStatus - from .dataconnectionerror import ( - DataConnectionError, - DataConnectionErrorTypedDict, - ErrorStatus, - ) - from .dataconnectionstatus import DataConnectionStatus - from .datastatus import DataStatus, DataStatusTypedDict, DataTypes - from .datatype import DataType - from .errorvalidation import ErrorValidation, ErrorValidationTypedDict - from .errorvalidationitem import ErrorValidationItem, ErrorValidationItemTypedDict - from .expensecontactref import ( - ExpenseContactRef, - ExpenseContactRefType, - ExpenseContactRefTypedDict, - ) - from .expensessyncwebhook import ExpensesSyncWebhook, ExpensesSyncWebhookTypedDict - from .expensessyncwebhookpayload import ( - ExpensesSyncWebhookPayload, - ExpensesSyncWebhookPayloadTypedDict, - ) - from .expensetransaction import ( - BankAccountReference, - BankAccountReferenceTypedDict, - ExpenseTransaction, - ExpenseTransactionType, - ExpenseTransactionTypedDict, - ) - from .expensetransactionline import ( - ExpenseTransactionLine, - ExpenseTransactionLineTypedDict, - ) - from .halref import HalRef, HalRefTypedDict - from .integrationtype import IntegrationType - from .invoiceto import InvoiceTo, InvoiceToType, InvoiceToTypedDict - from .itemref import ItemRef, ItemRefTypedDict - from .items import Items, ItemsTypedDict - from .links import Links, LinksTypedDict - from .mappingoptions import MappingOptions, MappingOptionsTypedDict - from .metadata import Metadata, MetadataTypedDict - from .phonenumber_items import PhoneNumberItems, PhoneNumberItemsTypedDict, Type - from .pulloperation import DatasetStatus, PullOperation, PullOperationTypedDict - from .pulloperations import PullOperations, PullOperationsTypedDict - from .pushchangetype import PushChangeType - from .pushfieldvalidation import PushFieldValidation, PushFieldValidationTypedDict - from .pushoperation import PushOperation, PushOperationTypedDict - from .pushoperationchange import PushOperationChange, PushOperationChangeTypedDict - from .pushoperationref import PushOperationRef, PushOperationRefTypedDict - from .pushoperations import PushOperations, PushOperationsTypedDict - from .pushoperationstatus import PushOperationStatus - from .pushoption import PushOption, PushOptionTypedDict - from .pushoptionchoice import PushOptionChoice, PushOptionChoiceTypedDict - from .pushoptionproperty import PushOptionProperty, PushOptionPropertyTypedDict - from .pushoptiontype import PushOptionType - from .pushvalidationinfo import PushValidationInfo, PushValidationInfoTypedDict - from .recordref import RecordRef, RecordRefTypedDict - from .reimbursableexpensetransaction import ( - ReimbursableExpenseTransaction, - ReimbursableExpenseTransactionTypedDict, - ) - from .reimbursableexpensetransactionline import ( - ReimbursableExpenseTransactionLine, - ReimbursableExpenseTransactionLineTypedDict, - ) - from .reimbursementcontactref import ( - ReimbursementContactRef, - ReimbursementContactRefTypedDict, - ) - from .schema_datatype import SchemaDataType - from .schema_transaction import SchemaTransaction, SchemaTransactionTypedDict from .security import Security, SecurityTypedDict - from .status import Status - from .supplementaldata import SupplementalData, SupplementalDataTypedDict - from .supplier import Supplier, SupplierTypedDict - from .supplierdetails import SupplierDetails, SupplierDetailsTypedDict - from .suppliers import Suppliers, SuppliersTypedDict - from .supplierstatus import SupplierStatus - from .taxratemappinginfo import TaxRateMappingInfo, TaxRateMappingInfoTypedDict - from .trackingcategorymappinginfo import ( - TrackingCategoryMappingInfo, - TrackingCategoryMappingInfoTypedDict, - ) - from .trackingref import TrackingRef, TrackingRefDataType, TrackingRefTypedDict - from .trackingrefadjustmenttransaction import ( - TrackingRefAdjustmentTransaction, - TrackingRefAdjustmentTransactionDataType, - TrackingRefAdjustmentTransactionTypedDict, - ) - from .transaction import ( - Transaction, - TransactionDefinitionsStatus, - TransactionTypedDict, - ) - from .transactions import Transactions, TransactionsTypedDict - from .transactionstatus import TransactionStatus - from .transfertransactionrequest import ( - AccountReference, - AccountReferenceTypedDict, - From, - FromTypedDict, - To, - ToTypedDict, - TransferTransactionRequest, - TransferTransactionRequestAccountReference, - TransferTransactionRequestAccountReferenceTypedDict, - TransferTransactionRequestTypedDict, - ) - from .transfertransactionresponse import ( - TransferTransactionResponse, - TransferTransactionResponseTypedDict, - ) - from .updatecustomerresponse import ( - UpdateCustomerResponse, - UpdateCustomerResponseAccountingCustomer, - UpdateCustomerResponseAccountingCustomerTypedDict, - UpdateCustomerResponseTypedDict, - ) - from .updateexpenserequest import ( - UpdateExpenseRequest, - UpdateExpenseRequestBankAccountReference, - UpdateExpenseRequestBankAccountReferenceTypedDict, - UpdateExpenseRequestType, - UpdateExpenseRequestTypedDict, - ) - from .updateexpenseresponse import ( - UpdateExpenseResponse, - UpdateExpenseResponseTypedDict, - ) - from .updatereimbursableexpensetransactionrequest import ( - UpdateReimbursableExpenseTransactionRequest, - UpdateReimbursableExpenseTransactionRequestTypedDict, - ) - from .updatesupplierresponse import ( - UpdateSupplierResponse, - UpdateSupplierResponseAccountingSupplier, - UpdateSupplierResponseAccountingSupplierTypedDict, - UpdateSupplierResponseTypedDict, - ) - from .validation import Validation, ValidationTypedDict - from .validationitem import ValidationItem, ValidationItemTypedDict - from .validfor import ValidFor - from .validtransactiontypes import ValidTransactionTypes - -__all__ = [ - "AccountMappingInfo", - "AccountMappingInfoAccountType", - "AccountMappingInfoTypedDict", - "AccountPrototype", - "AccountPrototypeTypedDict", - "AccountReference", - "AccountReferenceTypedDict", - "AccountStatus", - "AccountType", - "AccountingAccount", - "AccountingAccountTypedDict", - "AccountingAddress", - "AccountingAddressType", - "AccountingAddressTypedDict", - "AccountingBankAccount", - "AccountingBankAccountTypedDict", - "AccountingCustomer", - "AccountingCustomerTypedDict", - "AccountingSupplier", - "AccountingSupplierTypedDict", - "AdjustmentTransactionLine", - "AdjustmentTransactionLineTypedDict", - "AdjustmentTransactionRequest", - "AdjustmentTransactionRequestTypedDict", - "AdjustmentTransactionResponse", - "AdjustmentTransactionResponseTypedDict", - "ApAccountRef", - "ApAccountRefTypedDict", - "Attachment", - "AttachmentTypedDict", - "AttachmentUpload", - "AttachmentUploadTypedDict", - "BankAccount", - "BankAccountDetails", - "BankAccountDetailsTypedDict", - "BankAccountReference", - "BankAccountReferenceTypedDict", - "BankAccountStatus", - "BankAccountType", - "BankAccountTypedDict", - "ClientRateLimitWebhook", - "ClientRateLimitWebhookPayload", - "ClientRateLimitWebhookPayloadTypedDict", - "ClientRateLimitWebhookTypedDict", - "CodatFile", - "CodatFileTypedDict", - "Companies", - "CompaniesTypedDict", - "Company", - "CompanyConfiguration", - "CompanyConfigurationTypedDict", - "CompanyInformation", - "CompanyInformationSchemasType", - "CompanyInformationType", - "CompanyInformationTypedDict", - "CompanyReference", - "CompanyReferenceLinks", - "CompanyReferenceLinksTypedDict", - "CompanyReferenceTypedDict", - "CompanyRequestBody", - "CompanyRequestBodyTypedDict", - "CompanySyncStatus", - "CompanySyncStatusTypedDict", - "CompanyTypedDict", - "CompanyUpdateRequest", - "CompanyUpdateRequestTypedDict", - "Connection", - "ConnectionTypedDict", - "Connections", - "ConnectionsTypedDict", - "Contact", - "ContactTypedDict", - "CreateAccountResponse", - "CreateAccountResponseMetadata", - "CreateAccountResponseMetadataTypedDict", - "CreateAccountResponseTypedDict", - "CreateAccountResponseValidDataTypeLinks", - "CreateAccountResponseValidDataTypeLinksTypedDict", - "CreateBankAccountResponse", - "CreateBankAccountResponseBankAccountType", - "CreateBankAccountResponseTypedDict", - "CreateCustomerResponse", - "CreateCustomerResponseTypedDict", - "CreateExpenseResponse", - "CreateExpenseResponseTypedDict", - "CreateReimbursableExpenseResponse", - "CreateReimbursableExpenseResponseTypedDict", - "CreateSupplierResponse", - "CreateSupplierResponseTypedDict", - "Customer", - "CustomerDetails", - "CustomerDetailsTypedDict", - "CustomerStatus", - "CustomerTypedDict", - "Customers", - "CustomersTypedDict", - "DataConnectionError", - "DataConnectionErrorTypedDict", - "DataConnectionStatus", - "DataStatus", - "DataStatusTypedDict", - "DataType", - "DataTypes", - "DatasetStatus", - "ErrorStatus", - "ErrorValidation", - "ErrorValidationItem", - "ErrorValidationItemTypedDict", - "ErrorValidationTypedDict", - "ExpenseContactRef", - "ExpenseContactRefType", - "ExpenseContactRefTypedDict", - "ExpenseTransaction", - "ExpenseTransactionLine", - "ExpenseTransactionLineTypedDict", - "ExpenseTransactionType", - "ExpenseTransactionTypedDict", - "ExpensesSyncWebhook", - "ExpensesSyncWebhookPayload", - "ExpensesSyncWebhookPayloadTypedDict", - "ExpensesSyncWebhookTypedDict", - "From", - "FromTypedDict", - "HalRef", - "HalRefTypedDict", - "IntegrationType", - "InvoiceTo", - "InvoiceToType", - "InvoiceToTypedDict", - "ItemRef", - "ItemRefTypedDict", - "Items", - "ItemsTypedDict", - "Links", - "LinksTypedDict", - "MappingOptions", - "MappingOptionsTypedDict", - "Metadata", - "MetadataTypedDict", - "Phone", - "PhoneNumberItems", - "PhoneNumberItemsTypedDict", - "PhoneTypedDict", - "PullOperation", - "PullOperationTypedDict", - "PullOperations", - "PullOperationsTypedDict", - "PushChangeType", - "PushFieldValidation", - "PushFieldValidationTypedDict", - "PushOperation", - "PushOperationChange", - "PushOperationChangeTypedDict", - "PushOperationRef", - "PushOperationRefTypedDict", - "PushOperationStatus", - "PushOperationTypedDict", - "PushOperations", - "PushOperationsTypedDict", - "PushOption", - "PushOptionChoice", - "PushOptionChoiceTypedDict", - "PushOptionProperty", - "PushOptionPropertyTypedDict", - "PushOptionType", - "PushOptionTypedDict", - "PushValidationInfo", - "PushValidationInfoTypedDict", - "RecordRef", - "RecordRefTypedDict", - "ReimbursableExpenseTransaction", - "ReimbursableExpenseTransactionLine", - "ReimbursableExpenseTransactionLineTypedDict", - "ReimbursableExpenseTransactionTypedDict", - "ReimbursementContactRef", - "ReimbursementContactRefTypedDict", - "SchemaDataType", - "SchemaTransaction", - "SchemaTransactionTypedDict", - "Security", - "SecurityTypedDict", - "SourceType", - "Status", - "SupplementalData", - "SupplementalDataTypedDict", - "Supplier", - "SupplierDetails", - "SupplierDetailsTypedDict", - "SupplierStatus", - "SupplierTypedDict", - "Suppliers", - "SuppliersTypedDict", - "TaxRateMappingInfo", - "TaxRateMappingInfoTypedDict", - "To", - "ToTypedDict", - "TrackingCategoryMappingInfo", - "TrackingCategoryMappingInfoTypedDict", - "TrackingRef", - "TrackingRefAdjustmentTransaction", - "TrackingRefAdjustmentTransactionDataType", - "TrackingRefAdjustmentTransactionTypedDict", - "TrackingRefDataType", - "TrackingRefTypedDict", - "Transaction", - "TransactionDefinitionsStatus", - "TransactionStatus", - "TransactionTypedDict", - "Transactions", - "TransactionsTypedDict", - "TransferTransactionRequest", - "TransferTransactionRequestAccountReference", - "TransferTransactionRequestAccountReferenceTypedDict", - "TransferTransactionRequestTypedDict", - "TransferTransactionResponse", - "TransferTransactionResponseTypedDict", - "Type", - "UpdateCustomerResponse", - "UpdateCustomerResponseAccountingCustomer", - "UpdateCustomerResponseAccountingCustomerTypedDict", - "UpdateCustomerResponseTypedDict", - "UpdateExpenseRequest", - "UpdateExpenseRequestBankAccountReference", - "UpdateExpenseRequestBankAccountReferenceTypedDict", - "UpdateExpenseRequestType", - "UpdateExpenseRequestTypedDict", - "UpdateExpenseResponse", - "UpdateExpenseResponseTypedDict", - "UpdateReimbursableExpenseTransactionRequest", - "UpdateReimbursableExpenseTransactionRequestTypedDict", - "UpdateSupplierResponse", - "UpdateSupplierResponseAccountingSupplier", - "UpdateSupplierResponseAccountingSupplierTypedDict", - "UpdateSupplierResponseTypedDict", - "ValidDataTypeLinks", - "ValidDataTypeLinksTypedDict", - "ValidFor", - "ValidTransactionTypes", - "Validation", - "ValidationItem", - "ValidationItemTypedDict", - "ValidationTypedDict", - "Weblink", - "WeblinkTypedDict", -] + from codat_sync_for_expenses.models.account import Account, AccountTypedDict + from codat_sync_for_expenses.models.shared.accountmappinginfo import AccountMappingInfo, AccountMappingInfoTypedDict + from codat_sync_for_expenses.models.account_mapping_info_account_type import AccountMappingInfoAccountType + from codat_sync_for_expenses.models.shared.accountprototype import AccountPrototype, AccountPrototypeTypedDict + from codat_sync_for_expenses.models.account_reference import AccountReference, AccountReferenceTypedDict + from codat_sync_for_expenses.models.account_reference1 import AccountReference1, AccountReference1TypedDict + from codat_sync_for_expenses.models.shared.accountstatus import AccountStatus + from codat_sync_for_expenses.models.shared.accounttype import AccountType + from codat_sync_for_expenses.models.accounting_address import AccountingAddress, AccountingAddressTypedDict + from codat_sync_for_expenses.models.shared.accountingaddresstype import AccountingAddressType + from codat_sync_for_expenses.models.shared.adjustmenttransactionline import AdjustmentTransactionLine, AdjustmentTransactionLineTypedDict + from codat_sync_for_expenses.models.shared.adjustmenttransactionrequest import AdjustmentTransactionRequest, AdjustmentTransactionRequestTypedDict + from codat_sync_for_expenses.models.shared.adjustmenttransactionresponse import AdjustmentTransactionResponse, AdjustmentTransactionResponseTypedDict + from codat_sync_for_expenses.models.shared.apaccountref import ApAccountRef, ApAccountRefTypedDict + from codat_sync_for_expenses.models.shared.attachment import Attachment, AttachmentTypedDict + from codat_sync_for_expenses.models.shared.bankaccount import BankAccount, BankAccountTypedDict + from codat_sync_for_expenses.models.shared.bankaccountdetails import BankAccountDetails, BankAccountDetailsTypedDict + from codat_sync_for_expenses.models.bank_account_prototype import BankAccountPrototype, BankAccountPrototypeTypedDict + from codat_sync_for_expenses.models.bank_account_reference import BankAccountReference, BankAccountReferenceTypedDict + from codat_sync_for_expenses.models.shared.bankaccountstatus import BankAccountStatus + from codat_sync_for_expenses.models.bank_account_type import BankAccountType + from codat_sync_for_expenses.models.shared.clientratelimitwebhook import ClientRateLimitWebhook, ClientRateLimitWebhookTypedDict + from codat_sync_for_expenses.models.shared.clientratelimitwebhookpayload import ClientRateLimitWebhookPayload, ClientRateLimitWebhookPayloadTypedDict + from codat_sync_for_expenses.models.shared.companies import Companies, CompaniesTypedDict + from codat_sync_for_expenses.models.shared.company import Company, CompanyTypedDict + from codat_sync_for_expenses.models.shared.companyconfiguration import CompanyConfiguration, CompanyConfigurationTypedDict + from codat_sync_for_expenses.models.company_details import CompanyDetails, CompanyDetailsTypedDict + from codat_sync_for_expenses.models.company_information import CompanyInformation, CompanyInformationTypedDict + from codat_sync_for_expenses.models.company_information_type import CompanyInformationType + from codat_sync_for_expenses.models.shared.companyreference import CompanyReference, CompanyReferenceTypedDict + from codat_sync_for_expenses.models.company_reference_links import CompanyReferenceLinks, CompanyReferenceLinksTypedDict + from codat_sync_for_expenses.models.shared.companyrequestbody import CompanyRequestBody, CompanyRequestBodyTypedDict + from codat_sync_for_expenses.models.shared.companysyncstatus import CompanySyncStatus, CompanySyncStatusTypedDict + from codat_sync_for_expenses.models.shared.companyupdaterequest import CompanyUpdateRequest, CompanyUpdateRequestTypedDict + from codat_sync_for_expenses.models.shared.connection import Connection, ConnectionTypedDict + from codat_sync_for_expenses.models.shared.connections import Connections, ConnectionsTypedDict + from codat_sync_for_expenses.models.shared.contact import Contact, ContactTypedDict + from codat_sync_for_expenses.models.shared.createaccountresponse import CreateAccountResponse, CreateAccountResponseTypedDict + from codat_sync_for_expenses.models.create_account_response_all_of_data import CreateAccountResponseAllOfData, CreateAccountResponseAllOfDataTypedDict + from codat_sync_for_expenses.models.create_bank_account_response import CreateBankAccountResponse, CreateBankAccountResponseTypedDict + from codat_sync_for_expenses.models.create_bank_account_response_all_of_data import CreateBankAccountResponseAllOfData, CreateBankAccountResponseAllOfDataTypedDict + from codat_sync_for_expenses.models.create_connection_request import CreateConnectionRequest, CreateConnectionRequestTypedDict + from codat_sync_for_expenses.models.shared.createcustomerresponse import CreateCustomerResponse, CreateCustomerResponseTypedDict + from codat_sync_for_expenses.models.create_customer_response_all_of_data import CreateCustomerResponseAllOfData, CreateCustomerResponseAllOfDataTypedDict + from codat_sync_for_expenses.models.shared.createexpenseresponse import CreateExpenseResponse, CreateExpenseResponseTypedDict + from codat_sync_for_expenses.models.shared.createreimbursableexpenseresponse import CreateReimbursableExpenseResponse, CreateReimbursableExpenseResponseTypedDict + from codat_sync_for_expenses.models.shared.createsupplierresponse import CreateSupplierResponse, CreateSupplierResponseTypedDict + from codat_sync_for_expenses.models.create_supplier_response_all_of_data import CreateSupplierResponseAllOfData, CreateSupplierResponseAllOfDataTypedDict + from codat_sync_for_expenses.models.current_status import CurrentStatus + from codat_sync_for_expenses.models.shared.customer import Customer, CustomerTypedDict + from codat_sync_for_expenses.models.shared.customerdetails import CustomerDetails, CustomerDetailsTypedDict + from codat_sync_for_expenses.models.shared.customerstatus import CustomerStatus + from codat_sync_for_expenses.models.shared.customers import Customers, CustomersTypedDict + from codat_sync_for_expenses.models.shared.dataconnectionerror import DataConnectionError, DataConnectionErrorTypedDict + from codat_sync_for_expenses.models.shared.dataconnectionstatus import DataConnectionStatus + from codat_sync_for_expenses.models.shared.datastatus import DataStatus, DataStatusTypedDict + from codat_sync_for_expenses.models.data_statuses import DataStatuses, DataStatusesTypedDict + from codat_sync_for_expenses.models.shared.datatype import DataType + from codat_sync_for_expenses.models.data_types import DataTypes + from codat_sync_for_expenses.models.dataset_status import DatasetStatus + from codat_sync_for_expenses.models.error_message import ErrorMessage, ErrorMessageTypedDict + from codat_sync_for_expenses.models.error_status import ErrorStatus + from codat_sync_for_expenses.models.shared.errorvalidation import ErrorValidation, ErrorValidationTypedDict + from codat_sync_for_expenses.models.shared.errorvalidationitem import ErrorValidationItem, ErrorValidationItemTypedDict + from codat_sync_for_expenses.models.expense_contact_ref import ExpenseContactRef, ExpenseContactRefTypedDict + from codat_sync_for_expenses.models.shared.expensetransaction import ExpenseTransaction, ExpenseTransactionTypedDict + from codat_sync_for_expenses.models.shared.expensetransactionline import ExpenseTransactionLine, ExpenseTransactionLineTypedDict + from codat_sync_for_expenses.models.expense_transaction_type import ExpenseTransactionType + from codat_sync_for_expenses.models.shared.expensessyncwebhook import ExpensesSyncWebhook, ExpensesSyncWebhookTypedDict + from codat_sync_for_expenses.models.shared.expensessyncwebhookpayload import ExpensesSyncWebhookPayload, ExpensesSyncWebhookPayloadTypedDict + from codat_sync_for_expenses.models.expenses_sync_webhook_status import ExpensesSyncWebhookStatus + from codat_sync_for_expenses.models.shared.halref import HalRef, HalRefTypedDict + from codat_sync_for_expenses.models.shared.integrationtype import IntegrationType + from codat_sync_for_expenses.models.shared.invoiceto import InvoiceTo, InvoiceToTypedDict + from codat_sync_for_expenses.models.invoice_to_type import InvoiceToType + from codat_sync_for_expenses.models.shared.itemref import ItemRef, ItemRefTypedDict + from codat_sync_for_expenses.models.shared.items import Items, ItemsTypedDict + from codat_sync_for_expenses.models.shared.links import Links, LinksTypedDict + from codat_sync_for_expenses.models.shared.mappingoptions import MappingOptions, MappingOptionsTypedDict + from codat_sync_for_expenses.models.shared.metadata import Metadata, MetadataTypedDict + from codat_sync_for_expenses.models.model3 import Model3, Model3TypedDict + from codat_sync_for_expenses.models.paging_info import PagingInfo, PagingInfoTypedDict + from codat_sync_for_expenses.models.shared.phonenumber_items import PhoneNumberItems, PhoneNumberItemsTypedDict + from codat_sync_for_expenses.models.phone_number_items_type import PhoneNumberItemsType + from codat_sync_for_expenses.models.shared.pulloperation import PullOperation, PullOperationTypedDict + from codat_sync_for_expenses.models.shared.pulloperations import PullOperations, PullOperationsTypedDict + from codat_sync_for_expenses.models.shared.pushchangetype import PushChangeType + from codat_sync_for_expenses.models.shared.pushfieldvalidation import PushFieldValidation, PushFieldValidationTypedDict + from codat_sync_for_expenses.models.shared.pushoperation import PushOperation, PushOperationTypedDict + from codat_sync_for_expenses.models.shared.pushoperationchange import PushOperationChange, PushOperationChangeTypedDict + from codat_sync_for_expenses.models.shared.pushoperationref import PushOperationRef, PushOperationRefTypedDict + from codat_sync_for_expenses.models.shared.pushoperationstatus import PushOperationStatus + from codat_sync_for_expenses.models.shared.pushoperations import PushOperations, PushOperationsTypedDict + from codat_sync_for_expenses.models.shared.pushoption import PushOption, PushOptionTypedDict + from codat_sync_for_expenses.models.shared.pushoptionchoice import PushOptionChoice, PushOptionChoiceTypedDict + from codat_sync_for_expenses.models.shared.pushoptionproperty import PushOptionProperty, PushOptionPropertyTypedDict + from codat_sync_for_expenses.models.shared.pushoptiontype import PushOptionType + from codat_sync_for_expenses.models.shared.pushvalidationinfo import PushValidationInfo, PushValidationInfoTypedDict + from codat_sync_for_expenses.models.shared.recordref import RecordRef, RecordRefTypedDict + from codat_sync_for_expenses.models.shared.reimbursableexpensetransaction import ReimbursableExpenseTransaction, ReimbursableExpenseTransactionTypedDict + from codat_sync_for_expenses.models.shared.reimbursableexpensetransactionline import ReimbursableExpenseTransactionLine, ReimbursableExpenseTransactionLineTypedDict + from codat_sync_for_expenses.models.shared.reimbursementcontactref import ReimbursementContactRef, ReimbursementContactRefTypedDict + from codat_sync_for_expenses.models.shared.schema_transaction import SchemaTransaction, SchemaTransactionTypedDict + from codat_sync_for_expenses.models.source_type import SourceType + from codat_sync_for_expenses.models.shared.status import Status + from codat_sync_for_expenses.models.shared.supplementaldata import SupplementalData, SupplementalDataTypedDict + from codat_sync_for_expenses.models.shared.supplier import Supplier, SupplierTypedDict + from codat_sync_for_expenses.models.shared.supplierdetails import SupplierDetails, SupplierDetailsTypedDict + from codat_sync_for_expenses.models.shared.supplierstatus import SupplierStatus + from codat_sync_for_expenses.models.shared.suppliers import Suppliers, SuppliersTypedDict + from codat_sync_for_expenses.models.sync_complete_webhook import SyncCompleteWebhook, SyncCompleteWebhookTypedDict + from codat_sync_for_expenses.models.sync_complete_webhook_data import SyncCompleteWebhookData, SyncCompleteWebhookDataTypedDict + from codat_sync_for_expenses.models.sync_failed_webhook import SyncFailedWebhook, SyncFailedWebhookTypedDict + from codat_sync_for_expenses.models.sync_failed_webhook_data import SyncFailedWebhookData, SyncFailedWebhookDataTypedDict + from codat_sync_for_expenses.models.sync_initiated import SyncInitiated, SyncInitiatedTypedDict + from codat_sync_for_expenses.models.shared.taxratemappinginfo import TaxRateMappingInfo, TaxRateMappingInfoTypedDict + from codat_sync_for_expenses.models.shared.trackingcategorymappinginfo import TrackingCategoryMappingInfo, TrackingCategoryMappingInfoTypedDict + from codat_sync_for_expenses.models.shared.trackingref import TrackingRef, TrackingRefTypedDict + from codat_sync_for_expenses.models.shared.trackingrefadjustmenttransaction import TrackingRefAdjustmentTransaction, TrackingRefAdjustmentTransactionTypedDict + from codat_sync_for_expenses.models.tracking_ref_adjustment_transaction_data_type import TrackingRefAdjustmentTransactionDataType + from codat_sync_for_expenses.models.tracking_ref_data_type import TrackingRefDataType + from codat_sync_for_expenses.models.transaction import Transaction, TransactionTypedDict + from codat_sync_for_expenses.models.shared.transactionstatus import TransactionStatus + from codat_sync_for_expenses.models.shared.transactions import Transactions, TransactionsTypedDict + from codat_sync_for_expenses.models.shared.transfertransactionrequest import TransferTransactionRequest, TransferTransactionRequestTypedDict + from codat_sync_for_expenses.models.transfer_transaction_request_from import TransferTransactionRequestFrom, TransferTransactionRequestFromTypedDict + from codat_sync_for_expenses.models.transfer_transaction_request_to import TransferTransactionRequestTo, TransferTransactionRequestToTypedDict + from codat_sync_for_expenses.models.shared.transfertransactionresponse import TransferTransactionResponse, TransferTransactionResponseTypedDict + from codat_sync_for_expenses.models.type import Type + from codat_sync_for_expenses.models.update_connection import UpdateConnection, UpdateConnectionTypedDict + from codat_sync_for_expenses.models.shared.updatecustomerresponse import UpdateCustomerResponse, UpdateCustomerResponseTypedDict + from codat_sync_for_expenses.models.update_customer_response_all_of_data import UpdateCustomerResponseAllOfData, UpdateCustomerResponseAllOfDataTypedDict + from codat_sync_for_expenses.models.shared.updateexpenserequest import UpdateExpenseRequest, UpdateExpenseRequestTypedDict + from codat_sync_for_expenses.models.update_expense_request_type import UpdateExpenseRequestType + from codat_sync_for_expenses.models.shared.updateexpenseresponse import UpdateExpenseResponse, UpdateExpenseResponseTypedDict + from codat_sync_for_expenses.models.shared.updatereimbursableexpensetransactionrequest import UpdateReimbursableExpenseTransactionRequest, UpdateReimbursableExpenseTransactionRequestTypedDict + from codat_sync_for_expenses.models.shared.updatesupplierresponse import UpdateSupplierResponse, UpdateSupplierResponseTypedDict + from codat_sync_for_expenses.models.update_supplier_response_all_of_data import UpdateSupplierResponseAllOfData, UpdateSupplierResponseAllOfDataTypedDict + from codat_sync_for_expenses.models.valid_data_type_links import ValidDataTypeLinks, ValidDataTypeLinksTypedDict + from codat_sync_for_expenses.models.shared.validfor import ValidFor + from codat_sync_for_expenses.models.shared.validtransactiontypes import ValidTransactionTypes + from codat_sync_for_expenses.models.shared.validation import Validation, ValidationTypedDict + from codat_sync_for_expenses.models.shared.validationitem import ValidationItem, ValidationItemTypedDict + from codat_sync_for_expenses.models.weblink import Weblink, WeblinkTypedDict + from codat_sync_for_expenses.models.shared.companyinformation import CompanyInformationSchemasType + from codat_sync_for_expenses.models.shared.createbankaccountresponse import CreateBankAccountResponseBankAccountType + from codat_sync_for_expenses.models.shared.schema_datatype import SchemaDataType + from codat_sync_for_expenses.models.shared.transaction import TransactionDefinitionsStatus + from codat_sync_for_expenses.models.account_mapping_info_account_type import AccountMappingInfoAccountType as AccountMappingInfoAccountType + from codat_sync_for_expenses.models.shared.accountmappinginfo import AccountMappingInfoTypedDict as AccountMappingInfoTypedDict + from codat_sync_for_expenses.models.shared.accountprototype import AccountPrototypeTypedDict as AccountPrototypeTypedDict + from codat_sync_for_expenses.models.account_reference import AccountReferenceTypedDict as AccountReferenceTypedDict + from codat_sync_for_expenses.models.shared.accountstatus import AccountStatus as AccountStatus + from codat_sync_for_expenses.models.shared.accounttype import AccountType as AccountType + from codat_sync_for_expenses.models.create_account_response_all_of_data import CreateAccountResponseAllOfData as AccountingAccount + from codat_sync_for_expenses.models.create_account_response_all_of_data import CreateAccountResponseAllOfData as AccountingAccountTypedDict + from codat_sync_for_expenses.models.shared.accountingaddresstype import AccountingAddressType as AccountingAddressType + from codat_sync_for_expenses.models.accounting_address import AccountingAddressTypedDict as AccountingAddressTypedDict + from codat_sync_for_expenses.models.create_bank_account_response_all_of_data import CreateBankAccountResponseAllOfData as AccountingBankAccount + from codat_sync_for_expenses.models.create_bank_account_response_all_of_data import CreateBankAccountResponseAllOfData as AccountingBankAccountTypedDict + from codat_sync_for_expenses.models.create_customer_response_all_of_data import CreateCustomerResponseAllOfData as AccountingCustomer + from codat_sync_for_expenses.models.create_customer_response_all_of_data import CreateCustomerResponseAllOfData as AccountingCustomerTypedDict + from codat_sync_for_expenses.models.create_supplier_response_all_of_data import CreateSupplierResponseAllOfData as AccountingSupplier + from codat_sync_for_expenses.models.create_supplier_response_all_of_data import CreateSupplierResponseAllOfData as AccountingSupplierTypedDict + from codat_sync_for_expenses.models.shared.adjustmenttransactionline import AdjustmentTransactionLineTypedDict as AdjustmentTransactionLineTypedDict + from codat_sync_for_expenses.models.shared.adjustmenttransactionrequest import AdjustmentTransactionRequestTypedDict as AdjustmentTransactionRequestTypedDict + from codat_sync_for_expenses.models.shared.adjustmenttransactionresponse import AdjustmentTransactionResponseTypedDict as AdjustmentTransactionResponseTypedDict + from codat_sync_for_expenses.models.shared.apaccountref import ApAccountRefTypedDict as ApAccountRefTypedDict + from codat_sync_for_expenses.models.shared.attachment import AttachmentTypedDict as AttachmentTypedDict + from codat_sync_for_expenses.models.shared.bankaccountdetails import BankAccountDetailsTypedDict as BankAccountDetailsTypedDict + from codat_sync_for_expenses.models.bank_account_reference import BankAccountReferenceTypedDict as BankAccountReferenceTypedDict + from codat_sync_for_expenses.models.shared.bankaccountstatus import BankAccountStatus as BankAccountStatus + from codat_sync_for_expenses.models.bank_account_type import BankAccountType as BankAccountType + from codat_sync_for_expenses.models.shared.bankaccount import BankAccountTypedDict as BankAccountTypedDict + from codat_sync_for_expenses.models.shared.clientratelimitwebhookpayload import ClientRateLimitWebhookPayloadTypedDict as ClientRateLimitWebhookPayloadTypedDict + from codat_sync_for_expenses.models.shared.clientratelimitwebhook import ClientRateLimitWebhookTypedDict as ClientRateLimitWebhookTypedDict + from codat_sync_for_expenses.models.shared.companies import CompaniesTypedDict as CompaniesTypedDict + from codat_sync_for_expenses.models.shared.companyconfiguration import CompanyConfigurationTypedDict as CompanyConfigurationTypedDict + from codat_sync_for_expenses.models.shared.companyinformation import CompanyInformationSchemasType as CompanyInformationSchemasType + from codat_sync_for_expenses.models.company_information_type import CompanyInformationType as CompanyInformationType + from codat_sync_for_expenses.models.company_information import CompanyInformationTypedDict as CompanyInformationTypedDict + from codat_sync_for_expenses.models.company_reference_links import CompanyReferenceLinksTypedDict as CompanyReferenceLinksTypedDict + from codat_sync_for_expenses.models.shared.companyreference import CompanyReferenceTypedDict as CompanyReferenceTypedDict + from codat_sync_for_expenses.models.shared.companyrequestbody import CompanyRequestBodyTypedDict as CompanyRequestBodyTypedDict + from codat_sync_for_expenses.models.shared.companysyncstatus import CompanySyncStatusTypedDict as CompanySyncStatusTypedDict + from codat_sync_for_expenses.models.shared.company import CompanyTypedDict as CompanyTypedDict + from codat_sync_for_expenses.models.shared.companyupdaterequest import CompanyUpdateRequestTypedDict as CompanyUpdateRequestTypedDict + from codat_sync_for_expenses.models.shared.connection import ConnectionTypedDict as ConnectionTypedDict + from codat_sync_for_expenses.models.shared.connections import ConnectionsTypedDict as ConnectionsTypedDict + from codat_sync_for_expenses.models.shared.contact import ContactTypedDict as ContactTypedDict + from codat_sync_for_expenses.models.shared.metadata import Metadata as CreateAccountResponseMetadata + from codat_sync_for_expenses.models.shared.metadata import MetadataTypedDict as CreateAccountResponseMetadataTypedDict + from codat_sync_for_expenses.models.shared.createaccountresponse import CreateAccountResponseTypedDict as CreateAccountResponseTypedDict + from codat_sync_for_expenses.models.valid_data_type_links import ValidDataTypeLinks as CreateAccountResponseValidDataTypeLinks + from codat_sync_for_expenses.models.valid_data_type_links import ValidDataTypeLinksTypedDict as CreateAccountResponseValidDataTypeLinksTypedDict + from codat_sync_for_expenses.models.shared.createbankaccountresponse import CreateBankAccountResponseBankAccountType as CreateBankAccountResponseBankAccountType + from codat_sync_for_expenses.models.create_bank_account_response import CreateBankAccountResponseTypedDict as CreateBankAccountResponseTypedDict + from codat_sync_for_expenses.models.shared.createcustomerresponse import CreateCustomerResponseTypedDict as CreateCustomerResponseTypedDict + from codat_sync_for_expenses.models.shared.createexpenseresponse import CreateExpenseResponseTypedDict as CreateExpenseResponseTypedDict + from codat_sync_for_expenses.models.shared.createreimbursableexpenseresponse import CreateReimbursableExpenseResponseTypedDict as CreateReimbursableExpenseResponseTypedDict + from codat_sync_for_expenses.models.shared.createsupplierresponse import CreateSupplierResponseTypedDict as CreateSupplierResponseTypedDict + from codat_sync_for_expenses.models.shared.customerdetails import CustomerDetailsTypedDict as CustomerDetailsTypedDict + from codat_sync_for_expenses.models.shared.customerstatus import CustomerStatus as CustomerStatus + from codat_sync_for_expenses.models.shared.customer import CustomerTypedDict as CustomerTypedDict + from codat_sync_for_expenses.models.shared.customers import CustomersTypedDict as CustomersTypedDict + from codat_sync_for_expenses.models.shared.dataconnectionerror import DataConnectionErrorTypedDict as DataConnectionErrorTypedDict + from codat_sync_for_expenses.models.shared.dataconnectionstatus import DataConnectionStatus as DataConnectionStatus + from codat_sync_for_expenses.models.shared.datastatus import DataStatusTypedDict as DataStatusTypedDict + from codat_sync_for_expenses.models.shared.datatype import DataType as DataType + from codat_sync_for_expenses.models.data_types import DataTypes as DataTypes + from codat_sync_for_expenses.models.dataset_status import DatasetStatus as DatasetStatus + from codat_sync_for_expenses.models.error_status import ErrorStatus as ErrorStatus + from codat_sync_for_expenses.models.shared.errorvalidationitem import ErrorValidationItemTypedDict as ErrorValidationItemTypedDict + from codat_sync_for_expenses.models.shared.errorvalidation import ErrorValidationTypedDict as ErrorValidationTypedDict + from codat_sync_for_expenses.models.shared.expensecontactref import ExpenseContactRefType as ExpenseContactRefType + from codat_sync_for_expenses.models.expense_contact_ref import ExpenseContactRefTypedDict as ExpenseContactRefTypedDict + from codat_sync_for_expenses.models.shared.expensetransactionline import ExpenseTransactionLineTypedDict as ExpenseTransactionLineTypedDict + from codat_sync_for_expenses.models.expense_transaction_type import ExpenseTransactionType as ExpenseTransactionType + from codat_sync_for_expenses.models.shared.expensetransaction import ExpenseTransactionTypedDict as ExpenseTransactionTypedDict + from codat_sync_for_expenses.models.shared.expensessyncwebhookpayload import ExpensesSyncWebhookPayloadTypedDict as ExpensesSyncWebhookPayloadTypedDict + from codat_sync_for_expenses.models.shared.expensessyncwebhook import ExpensesSyncWebhookTypedDict as ExpensesSyncWebhookTypedDict + from codat_sync_for_expenses.models.transfer_transaction_request_from import TransferTransactionRequestFrom as From + from codat_sync_for_expenses.models.transfer_transaction_request_from import TransferTransactionRequestFromTypedDict as FromTypedDict + from codat_sync_for_expenses.models.shared.halref import HalRefTypedDict as HalRefTypedDict + from codat_sync_for_expenses.models.shared.integrationtype import IntegrationType as IntegrationType + from codat_sync_for_expenses.models.invoice_to_type import InvoiceToType as InvoiceToType + from codat_sync_for_expenses.models.shared.invoiceto import InvoiceToTypedDict as InvoiceToTypedDict + from codat_sync_for_expenses.models.shared.itemref import ItemRefTypedDict as ItemRefTypedDict + from codat_sync_for_expenses.models.shared.items import ItemsTypedDict as ItemsTypedDict + from codat_sync_for_expenses.models.shared.links import LinksTypedDict as LinksTypedDict + from codat_sync_for_expenses.models.shared.mappingoptions import MappingOptionsTypedDict as MappingOptionsTypedDict + from codat_sync_for_expenses.models.shared.metadata import MetadataTypedDict as MetadataTypedDict + from codat_sync_for_expenses.models.shared.phonenumber_items import PhoneNumberItems as Phone + from codat_sync_for_expenses.models.shared.phonenumber_items import PhoneNumberItemsTypedDict as PhoneNumberItemsTypedDict + from codat_sync_for_expenses.models.shared.phonenumber_items import PhoneNumberItemsTypedDict as PhoneTypedDict + from codat_sync_for_expenses.models.shared.pulloperation import PullOperationTypedDict as PullOperationTypedDict + from codat_sync_for_expenses.models.shared.pulloperations import PullOperationsTypedDict as PullOperationsTypedDict + from codat_sync_for_expenses.models.shared.pushchangetype import PushChangeType as PushChangeType + from codat_sync_for_expenses.models.shared.pushfieldvalidation import PushFieldValidationTypedDict as PushFieldValidationTypedDict + from codat_sync_for_expenses.models.shared.pushoperationchange import PushOperationChangeTypedDict as PushOperationChangeTypedDict + from codat_sync_for_expenses.models.shared.pushoperationref import PushOperationRefTypedDict as PushOperationRefTypedDict + from codat_sync_for_expenses.models.shared.pushoperationstatus import PushOperationStatus as PushOperationStatus + from codat_sync_for_expenses.models.shared.pushoperation import PushOperationTypedDict as PushOperationTypedDict + from codat_sync_for_expenses.models.shared.pushoperations import PushOperationsTypedDict as PushOperationsTypedDict + from codat_sync_for_expenses.models.shared.pushoptionchoice import PushOptionChoiceTypedDict as PushOptionChoiceTypedDict + from codat_sync_for_expenses.models.shared.pushoptionproperty import PushOptionPropertyTypedDict as PushOptionPropertyTypedDict + from codat_sync_for_expenses.models.shared.pushoptiontype import PushOptionType as PushOptionType + from codat_sync_for_expenses.models.shared.pushoption import PushOptionTypedDict as PushOptionTypedDict + from codat_sync_for_expenses.models.shared.pushvalidationinfo import PushValidationInfoTypedDict as PushValidationInfoTypedDict + from codat_sync_for_expenses.models.shared.recordref import RecordRefTypedDict as RecordRefTypedDict + from codat_sync_for_expenses.models.shared.reimbursableexpensetransactionline import ReimbursableExpenseTransactionLineTypedDict as ReimbursableExpenseTransactionLineTypedDict + from codat_sync_for_expenses.models.shared.reimbursableexpensetransaction import ReimbursableExpenseTransactionTypedDict as ReimbursableExpenseTransactionTypedDict + from codat_sync_for_expenses.models.shared.reimbursementcontactref import ReimbursementContactRefTypedDict as ReimbursementContactRefTypedDict + from codat_sync_for_expenses.models.shared.schema_datatype import SchemaDataType as SchemaDataType + from codat_sync_for_expenses.models.shared.schema_transaction import SchemaTransactionTypedDict as SchemaTransactionTypedDict + from codat_sync_for_expenses.models.shared.security import Security as Security + from codat_sync_for_expenses.models.shared.security import SecurityTypedDict as SecurityTypedDict + from codat_sync_for_expenses.models.source_type import SourceType as SourceType + from codat_sync_for_expenses.models.shared.status import Status as Status + from codat_sync_for_expenses.models.shared.supplementaldata import SupplementalDataTypedDict as SupplementalDataTypedDict + from codat_sync_for_expenses.models.shared.supplierdetails import SupplierDetailsTypedDict as SupplierDetailsTypedDict + from codat_sync_for_expenses.models.shared.supplierstatus import SupplierStatus as SupplierStatus + from codat_sync_for_expenses.models.shared.supplier import SupplierTypedDict as SupplierTypedDict + from codat_sync_for_expenses.models.shared.suppliers import SuppliersTypedDict as SuppliersTypedDict + from codat_sync_for_expenses.models.shared.taxratemappinginfo import TaxRateMappingInfoTypedDict as TaxRateMappingInfoTypedDict + from codat_sync_for_expenses.models.transfer_transaction_request_to import TransferTransactionRequestTo as To + from codat_sync_for_expenses.models.transfer_transaction_request_to import TransferTransactionRequestToTypedDict as ToTypedDict + from codat_sync_for_expenses.models.shared.trackingcategorymappinginfo import TrackingCategoryMappingInfoTypedDict as TrackingCategoryMappingInfoTypedDict + from codat_sync_for_expenses.models.tracking_ref_adjustment_transaction_data_type import TrackingRefAdjustmentTransactionDataType as TrackingRefAdjustmentTransactionDataType + from codat_sync_for_expenses.models.shared.trackingrefadjustmenttransaction import TrackingRefAdjustmentTransactionTypedDict as TrackingRefAdjustmentTransactionTypedDict + from codat_sync_for_expenses.models.tracking_ref_data_type import TrackingRefDataType as TrackingRefDataType + from codat_sync_for_expenses.models.shared.trackingref import TrackingRefTypedDict as TrackingRefTypedDict + from codat_sync_for_expenses.models.shared.transaction import TransactionDefinitionsStatus as TransactionDefinitionsStatus + from codat_sync_for_expenses.models.shared.transactionstatus import TransactionStatus as TransactionStatus + from codat_sync_for_expenses.models.transaction import TransactionTypedDict as TransactionTypedDict + from codat_sync_for_expenses.models.shared.transactions import TransactionsTypedDict as TransactionsTypedDict + from codat_sync_for_expenses.models.account_reference import AccountReference as TransferTransactionRequestAccountReference + from codat_sync_for_expenses.models.account_reference import AccountReferenceTypedDict as TransferTransactionRequestAccountReferenceTypedDict + from codat_sync_for_expenses.models.shared.transfertransactionrequest import TransferTransactionRequestTypedDict as TransferTransactionRequestTypedDict + from codat_sync_for_expenses.models.shared.transfertransactionresponse import TransferTransactionResponseTypedDict as TransferTransactionResponseTypedDict + from codat_sync_for_expenses.models.type import Type as Type + from codat_sync_for_expenses.models.update_customer_response_all_of_data import UpdateCustomerResponseAllOfData as UpdateCustomerResponseAccountingCustomer + from codat_sync_for_expenses.models.update_customer_response_all_of_data import UpdateCustomerResponseAllOfData as UpdateCustomerResponseAccountingCustomerTypedDict + from codat_sync_for_expenses.models.shared.updatecustomerresponse import UpdateCustomerResponseTypedDict as UpdateCustomerResponseTypedDict + from codat_sync_for_expenses.models.bank_account_reference import BankAccountReference as UpdateExpenseRequestBankAccountReference + from codat_sync_for_expenses.models.bank_account_reference import BankAccountReferenceTypedDict as UpdateExpenseRequestBankAccountReferenceTypedDict + from codat_sync_for_expenses.models.update_expense_request_type import UpdateExpenseRequestType as UpdateExpenseRequestType + from codat_sync_for_expenses.models.shared.updateexpenserequest import UpdateExpenseRequestTypedDict as UpdateExpenseRequestTypedDict + from codat_sync_for_expenses.models.shared.updateexpenseresponse import UpdateExpenseResponseTypedDict as UpdateExpenseResponseTypedDict + from codat_sync_for_expenses.models.shared.updatereimbursableexpensetransactionrequest import UpdateReimbursableExpenseTransactionRequestTypedDict as UpdateReimbursableExpenseTransactionRequestTypedDict + from codat_sync_for_expenses.models.update_supplier_response_all_of_data import UpdateSupplierResponseAllOfData as UpdateSupplierResponseAccountingSupplier + from codat_sync_for_expenses.models.update_supplier_response_all_of_data import UpdateSupplierResponseAllOfData as UpdateSupplierResponseAccountingSupplierTypedDict + from codat_sync_for_expenses.models.shared.updatesupplierresponse import UpdateSupplierResponseTypedDict as UpdateSupplierResponseTypedDict + from codat_sync_for_expenses.models.valid_data_type_links import ValidDataTypeLinksTypedDict as ValidDataTypeLinksTypedDict + from codat_sync_for_expenses.models.shared.validfor import ValidFor as ValidFor + from codat_sync_for_expenses.models.shared.validtransactiontypes import ValidTransactionTypes as ValidTransactionTypes + from codat_sync_for_expenses.models.shared.validationitem import ValidationItemTypedDict as ValidationItemTypedDict + from codat_sync_for_expenses.models.shared.validation import ValidationTypedDict as ValidationTypedDict + from codat_sync_for_expenses.models.weblink import WeblinkTypedDict as WeblinkTypedDict + from codat_sync_for_expenses.models.shared.codatfile import CodatFile, CodatFileTypedDict + from codat_sync_for_expenses.models.shared.attachmentupload import AttachmentUpload, AttachmentUploadTypedDict -_dynamic_imports: dict[str, str] = { - "AccountingAddressType": ".accountingaddresstype", - "AccountMappingInfo": ".accountmappinginfo", - "AccountMappingInfoAccountType": ".accountmappinginfo", - "AccountMappingInfoTypedDict": ".accountmappinginfo", - "AccountPrototype": ".accountprototype", - "AccountPrototypeTypedDict": ".accountprototype", - "ValidDataTypeLinks": ".accountprototype", - "ValidDataTypeLinksTypedDict": ".accountprototype", - "AccountStatus": ".accountstatus", - "AccountType": ".accounttype", - "AdjustmentTransactionLine": ".adjustmenttransactionline", - "AdjustmentTransactionLineTypedDict": ".adjustmenttransactionline", - "AdjustmentTransactionRequest": ".adjustmenttransactionrequest", - "AdjustmentTransactionRequestTypedDict": ".adjustmenttransactionrequest", - "AdjustmentTransactionResponse": ".adjustmenttransactionresponse", - "AdjustmentTransactionResponseTypedDict": ".adjustmenttransactionresponse", - "ApAccountRef": ".apaccountref", - "ApAccountRefTypedDict": ".apaccountref", - "Attachment": ".attachment", - "AttachmentTypedDict": ".attachment", - "AttachmentUpload": ".attachmentupload", - "AttachmentUploadTypedDict": ".attachmentupload", - "BankAccount": ".bankaccount", - "BankAccountType": ".bankaccount", - "BankAccountTypedDict": ".bankaccount", - "BankAccountDetails": ".bankaccountdetails", - "BankAccountDetailsTypedDict": ".bankaccountdetails", - "BankAccountStatus": ".bankaccountstatus", - "ClientRateLimitWebhook": ".clientratelimitwebhook", - "ClientRateLimitWebhookTypedDict": ".clientratelimitwebhook", - "ClientRateLimitWebhookPayload": ".clientratelimitwebhookpayload", - "ClientRateLimitWebhookPayloadTypedDict": ".clientratelimitwebhookpayload", - "CodatFile": ".codatfile", - "CodatFileTypedDict": ".codatfile", - "Companies": ".companies", - "CompaniesTypedDict": ".companies", - "Company": ".company", - "CompanyTypedDict": ".company", - "CompanyConfiguration": ".companyconfiguration", - "CompanyConfigurationTypedDict": ".companyconfiguration", - "AccountingAddress": ".companyinformation", - "AccountingAddressTypedDict": ".companyinformation", - "CompanyInformation": ".companyinformation", - "CompanyInformationSchemasType": ".companyinformation", - "CompanyInformationType": ".companyinformation", - "CompanyInformationTypedDict": ".companyinformation", - "Phone": ".companyinformation", - "PhoneTypedDict": ".companyinformation", - "Weblink": ".companyinformation", - "WeblinkTypedDict": ".companyinformation", - "CompanyReference": ".companyreference", - "CompanyReferenceLinks": ".companyreference", - "CompanyReferenceLinksTypedDict": ".companyreference", - "CompanyReferenceTypedDict": ".companyreference", - "CompanyRequestBody": ".companyrequestbody", - "CompanyRequestBodyTypedDict": ".companyrequestbody", - "CompanySyncStatus": ".companysyncstatus", - "CompanySyncStatusTypedDict": ".companysyncstatus", - "CompanyUpdateRequest": ".companyupdaterequest", - "CompanyUpdateRequestTypedDict": ".companyupdaterequest", - "Connection": ".connection", - "ConnectionTypedDict": ".connection", - "SourceType": ".connection", - "Connections": ".connections", - "ConnectionsTypedDict": ".connections", - "Contact": ".contact", - "ContactTypedDict": ".contact", - "AccountingAccount": ".createaccountresponse", - "AccountingAccountTypedDict": ".createaccountresponse", - "CreateAccountResponse": ".createaccountresponse", - "CreateAccountResponseMetadata": ".createaccountresponse", - "CreateAccountResponseMetadataTypedDict": ".createaccountresponse", - "CreateAccountResponseTypedDict": ".createaccountresponse", - "CreateAccountResponseValidDataTypeLinks": ".createaccountresponse", - "CreateAccountResponseValidDataTypeLinksTypedDict": ".createaccountresponse", - "AccountingBankAccount": ".createbankaccountresponse", - "AccountingBankAccountTypedDict": ".createbankaccountresponse", - "CreateBankAccountResponse": ".createbankaccountresponse", - "CreateBankAccountResponseBankAccountType": ".createbankaccountresponse", - "CreateBankAccountResponseTypedDict": ".createbankaccountresponse", - "AccountingCustomer": ".createcustomerresponse", - "AccountingCustomerTypedDict": ".createcustomerresponse", - "CreateCustomerResponse": ".createcustomerresponse", - "CreateCustomerResponseTypedDict": ".createcustomerresponse", - "CreateExpenseResponse": ".createexpenseresponse", - "CreateExpenseResponseTypedDict": ".createexpenseresponse", - "CreateReimbursableExpenseResponse": ".createreimbursableexpenseresponse", - "CreateReimbursableExpenseResponseTypedDict": ".createreimbursableexpenseresponse", - "AccountingSupplier": ".createsupplierresponse", - "AccountingSupplierTypedDict": ".createsupplierresponse", - "CreateSupplierResponse": ".createsupplierresponse", - "CreateSupplierResponseTypedDict": ".createsupplierresponse", - "Customer": ".customer", - "CustomerTypedDict": ".customer", - "CustomerDetails": ".customerdetails", - "CustomerDetailsTypedDict": ".customerdetails", - "Customers": ".customers", - "CustomersTypedDict": ".customers", - "CustomerStatus": ".customerstatus", - "DataConnectionError": ".dataconnectionerror", - "DataConnectionErrorTypedDict": ".dataconnectionerror", - "ErrorStatus": ".dataconnectionerror", - "DataConnectionStatus": ".dataconnectionstatus", - "DataStatus": ".datastatus", - "DataStatusTypedDict": ".datastatus", - "DataTypes": ".datastatus", - "DataType": ".datatype", - "ErrorValidation": ".errorvalidation", - "ErrorValidationTypedDict": ".errorvalidation", - "ErrorValidationItem": ".errorvalidationitem", - "ErrorValidationItemTypedDict": ".errorvalidationitem", - "ExpenseContactRef": ".expensecontactref", - "ExpenseContactRefType": ".expensecontactref", - "ExpenseContactRefTypedDict": ".expensecontactref", - "ExpensesSyncWebhook": ".expensessyncwebhook", - "ExpensesSyncWebhookTypedDict": ".expensessyncwebhook", - "ExpensesSyncWebhookPayload": ".expensessyncwebhookpayload", - "ExpensesSyncWebhookPayloadTypedDict": ".expensessyncwebhookpayload", - "BankAccountReference": ".expensetransaction", - "BankAccountReferenceTypedDict": ".expensetransaction", - "ExpenseTransaction": ".expensetransaction", - "ExpenseTransactionType": ".expensetransaction", - "ExpenseTransactionTypedDict": ".expensetransaction", - "ExpenseTransactionLine": ".expensetransactionline", - "ExpenseTransactionLineTypedDict": ".expensetransactionline", - "HalRef": ".halref", - "HalRefTypedDict": ".halref", - "IntegrationType": ".integrationtype", - "InvoiceTo": ".invoiceto", - "InvoiceToType": ".invoiceto", - "InvoiceToTypedDict": ".invoiceto", - "ItemRef": ".itemref", - "ItemRefTypedDict": ".itemref", - "Items": ".items", - "ItemsTypedDict": ".items", - "Links": ".links", - "LinksTypedDict": ".links", - "MappingOptions": ".mappingoptions", - "MappingOptionsTypedDict": ".mappingoptions", - "Metadata": ".metadata", - "MetadataTypedDict": ".metadata", - "PhoneNumberItems": ".phonenumber_items", - "PhoneNumberItemsTypedDict": ".phonenumber_items", - "Type": ".phonenumber_items", - "DatasetStatus": ".pulloperation", - "PullOperation": ".pulloperation", - "PullOperationTypedDict": ".pulloperation", - "PullOperations": ".pulloperations", - "PullOperationsTypedDict": ".pulloperations", - "PushChangeType": ".pushchangetype", - "PushFieldValidation": ".pushfieldvalidation", - "PushFieldValidationTypedDict": ".pushfieldvalidation", - "PushOperation": ".pushoperation", - "PushOperationTypedDict": ".pushoperation", - "PushOperationChange": ".pushoperationchange", - "PushOperationChangeTypedDict": ".pushoperationchange", - "PushOperationRef": ".pushoperationref", - "PushOperationRefTypedDict": ".pushoperationref", - "PushOperations": ".pushoperations", - "PushOperationsTypedDict": ".pushoperations", - "PushOperationStatus": ".pushoperationstatus", - "PushOption": ".pushoption", - "PushOptionTypedDict": ".pushoption", - "PushOptionChoice": ".pushoptionchoice", - "PushOptionChoiceTypedDict": ".pushoptionchoice", - "PushOptionProperty": ".pushoptionproperty", - "PushOptionPropertyTypedDict": ".pushoptionproperty", - "PushOptionType": ".pushoptiontype", - "PushValidationInfo": ".pushvalidationinfo", - "PushValidationInfoTypedDict": ".pushvalidationinfo", - "RecordRef": ".recordref", - "RecordRefTypedDict": ".recordref", - "ReimbursableExpenseTransaction": ".reimbursableexpensetransaction", - "ReimbursableExpenseTransactionTypedDict": ".reimbursableexpensetransaction", - "ReimbursableExpenseTransactionLine": ".reimbursableexpensetransactionline", - "ReimbursableExpenseTransactionLineTypedDict": ".reimbursableexpensetransactionline", - "ReimbursementContactRef": ".reimbursementcontactref", - "ReimbursementContactRefTypedDict": ".reimbursementcontactref", - "SchemaDataType": ".schema_datatype", - "SchemaTransaction": ".schema_transaction", - "SchemaTransactionTypedDict": ".schema_transaction", - "Security": ".security", - "SecurityTypedDict": ".security", - "Status": ".status", - "SupplementalData": ".supplementaldata", - "SupplementalDataTypedDict": ".supplementaldata", - "Supplier": ".supplier", - "SupplierTypedDict": ".supplier", - "SupplierDetails": ".supplierdetails", - "SupplierDetailsTypedDict": ".supplierdetails", - "Suppliers": ".suppliers", - "SuppliersTypedDict": ".suppliers", - "SupplierStatus": ".supplierstatus", - "TaxRateMappingInfo": ".taxratemappinginfo", - "TaxRateMappingInfoTypedDict": ".taxratemappinginfo", - "TrackingCategoryMappingInfo": ".trackingcategorymappinginfo", - "TrackingCategoryMappingInfoTypedDict": ".trackingcategorymappinginfo", - "TrackingRef": ".trackingref", - "TrackingRefDataType": ".trackingref", - "TrackingRefTypedDict": ".trackingref", - "TrackingRefAdjustmentTransaction": ".trackingrefadjustmenttransaction", - "TrackingRefAdjustmentTransactionDataType": ".trackingrefadjustmenttransaction", - "TrackingRefAdjustmentTransactionTypedDict": ".trackingrefadjustmenttransaction", - "Transaction": ".transaction", - "TransactionDefinitionsStatus": ".transaction", - "TransactionTypedDict": ".transaction", - "Transactions": ".transactions", - "TransactionsTypedDict": ".transactions", - "TransactionStatus": ".transactionstatus", - "AccountReference": ".transfertransactionrequest", - "AccountReferenceTypedDict": ".transfertransactionrequest", - "From": ".transfertransactionrequest", - "FromTypedDict": ".transfertransactionrequest", - "To": ".transfertransactionrequest", - "ToTypedDict": ".transfertransactionrequest", - "TransferTransactionRequest": ".transfertransactionrequest", - "TransferTransactionRequestAccountReference": ".transfertransactionrequest", - "TransferTransactionRequestAccountReferenceTypedDict": ".transfertransactionrequest", - "TransferTransactionRequestTypedDict": ".transfertransactionrequest", - "TransferTransactionResponse": ".transfertransactionresponse", - "TransferTransactionResponseTypedDict": ".transfertransactionresponse", - "UpdateCustomerResponse": ".updatecustomerresponse", - "UpdateCustomerResponseAccountingCustomer": ".updatecustomerresponse", - "UpdateCustomerResponseAccountingCustomerTypedDict": ".updatecustomerresponse", - "UpdateCustomerResponseTypedDict": ".updatecustomerresponse", - "UpdateExpenseRequest": ".updateexpenserequest", - "UpdateExpenseRequestBankAccountReference": ".updateexpenserequest", - "UpdateExpenseRequestBankAccountReferenceTypedDict": ".updateexpenserequest", - "UpdateExpenseRequestType": ".updateexpenserequest", - "UpdateExpenseRequestTypedDict": ".updateexpenserequest", - "UpdateExpenseResponse": ".updateexpenseresponse", - "UpdateExpenseResponseTypedDict": ".updateexpenseresponse", - "UpdateReimbursableExpenseTransactionRequest": ".updatereimbursableexpensetransactionrequest", - "UpdateReimbursableExpenseTransactionRequestTypedDict": ".updatereimbursableexpensetransactionrequest", - "UpdateSupplierResponse": ".updatesupplierresponse", - "UpdateSupplierResponseAccountingSupplier": ".updatesupplierresponse", - "UpdateSupplierResponseAccountingSupplierTypedDict": ".updatesupplierresponse", - "UpdateSupplierResponseTypedDict": ".updatesupplierresponse", - "Validation": ".validation", - "ValidationTypedDict": ".validation", - "ValidationItem": ".validationitem", - "ValidationItemTypedDict": ".validationitem", - "ValidFor": ".validfor", - "ValidTransactionTypes": ".validtransactiontypes", +_dynamic_imports: dict[str, tuple[str, str]] = { + 'Account': ('codat_sync_for_expenses.models.account', 'Account'), + 'AccountMappingInfo': ('codat_sync_for_expenses.models.shared.accountmappinginfo', 'AccountMappingInfo'), + 'AccountMappingInfoAccountType': ('codat_sync_for_expenses.models.account_mapping_info_account_type', 'AccountMappingInfoAccountType'), + 'AccountMappingInfoTypedDict': ('codat_sync_for_expenses.models.shared.accountmappinginfo', 'AccountMappingInfoTypedDict'), + 'AccountPrototype': ('codat_sync_for_expenses.models.shared.accountprototype', 'AccountPrototype'), + 'AccountPrototypeTypedDict': ('codat_sync_for_expenses.models.shared.accountprototype', 'AccountPrototypeTypedDict'), + 'AccountReference': ('codat_sync_for_expenses.models.account_reference', 'AccountReference'), + 'AccountReference1': ('codat_sync_for_expenses.models.account_reference1', 'AccountReference1'), + 'AccountReference1TypedDict': ('codat_sync_for_expenses.models.account_reference1', 'AccountReference1TypedDict'), + 'AccountReferenceTypedDict': ('codat_sync_for_expenses.models.account_reference', 'AccountReferenceTypedDict'), + 'AccountStatus': ('codat_sync_for_expenses.models.shared.accountstatus', 'AccountStatus'), + 'AccountType': ('codat_sync_for_expenses.models.shared.accounttype', 'AccountType'), + 'AccountTypedDict': ('codat_sync_for_expenses.models.account', 'AccountTypedDict'), + 'AccountingAccount': ('codat_sync_for_expenses.models.create_account_response_all_of_data', 'CreateAccountResponseAllOfData'), + 'AccountingAccountTypedDict': ('codat_sync_for_expenses.models.create_account_response_all_of_data', 'CreateAccountResponseAllOfData'), + 'AccountingAddress': ('codat_sync_for_expenses.models.accounting_address', 'AccountingAddress'), + 'AccountingAddressType': ('codat_sync_for_expenses.models.shared.accountingaddresstype', 'AccountingAddressType'), + 'AccountingAddressTypedDict': ('codat_sync_for_expenses.models.accounting_address', 'AccountingAddressTypedDict'), + 'AccountingBankAccount': ('codat_sync_for_expenses.models.create_bank_account_response_all_of_data', 'CreateBankAccountResponseAllOfData'), + 'AccountingBankAccountTypedDict': ('codat_sync_for_expenses.models.create_bank_account_response_all_of_data', 'CreateBankAccountResponseAllOfData'), + 'AccountingCustomer': ('codat_sync_for_expenses.models.create_customer_response_all_of_data', 'CreateCustomerResponseAllOfData'), + 'AccountingCustomerTypedDict': ('codat_sync_for_expenses.models.create_customer_response_all_of_data', 'CreateCustomerResponseAllOfData'), + 'AccountingSupplier': ('codat_sync_for_expenses.models.create_supplier_response_all_of_data', 'CreateSupplierResponseAllOfData'), + 'AccountingSupplierTypedDict': ('codat_sync_for_expenses.models.create_supplier_response_all_of_data', 'CreateSupplierResponseAllOfData'), + 'AdjustmentTransactionLine': ('codat_sync_for_expenses.models.shared.adjustmenttransactionline', 'AdjustmentTransactionLine'), + 'AdjustmentTransactionLineTypedDict': ('codat_sync_for_expenses.models.shared.adjustmenttransactionline', 'AdjustmentTransactionLineTypedDict'), + 'AdjustmentTransactionRequest': ('codat_sync_for_expenses.models.shared.adjustmenttransactionrequest', 'AdjustmentTransactionRequest'), + 'AdjustmentTransactionRequestTypedDict': ('codat_sync_for_expenses.models.shared.adjustmenttransactionrequest', 'AdjustmentTransactionRequestTypedDict'), + 'AdjustmentTransactionResponse': ('codat_sync_for_expenses.models.shared.adjustmenttransactionresponse', 'AdjustmentTransactionResponse'), + 'AdjustmentTransactionResponseTypedDict': ('codat_sync_for_expenses.models.shared.adjustmenttransactionresponse', 'AdjustmentTransactionResponseTypedDict'), + 'ApAccountRef': ('codat_sync_for_expenses.models.shared.apaccountref', 'ApAccountRef'), + 'ApAccountRefTypedDict': ('codat_sync_for_expenses.models.shared.apaccountref', 'ApAccountRefTypedDict'), + 'Attachment': ('codat_sync_for_expenses.models.shared.attachment', 'Attachment'), + 'AttachmentTypedDict': ('codat_sync_for_expenses.models.shared.attachment', 'AttachmentTypedDict'), + 'AttachmentUpload': ('codat_sync_for_expenses.models.shared.attachmentupload', 'AttachmentUpload'), + 'AttachmentUploadTypedDict': ('codat_sync_for_expenses.models.shared.attachmentupload', 'AttachmentUploadTypedDict'), + 'BankAccount': ('codat_sync_for_expenses.models.shared.bankaccount', 'BankAccount'), + 'BankAccountDetails': ('codat_sync_for_expenses.models.shared.bankaccountdetails', 'BankAccountDetails'), + 'BankAccountDetailsTypedDict': ('codat_sync_for_expenses.models.shared.bankaccountdetails', 'BankAccountDetailsTypedDict'), + 'BankAccountPrototype': ('codat_sync_for_expenses.models.bank_account_prototype', 'BankAccountPrototype'), + 'BankAccountPrototypeTypedDict': ('codat_sync_for_expenses.models.bank_account_prototype', 'BankAccountPrototypeTypedDict'), + 'BankAccountReference': ('codat_sync_for_expenses.models.bank_account_reference', 'BankAccountReference'), + 'BankAccountReferenceTypedDict': ('codat_sync_for_expenses.models.bank_account_reference', 'BankAccountReferenceTypedDict'), + 'BankAccountStatus': ('codat_sync_for_expenses.models.shared.bankaccountstatus', 'BankAccountStatus'), + 'BankAccountType': ('codat_sync_for_expenses.models.bank_account_type', 'BankAccountType'), + 'BankAccountTypedDict': ('codat_sync_for_expenses.models.shared.bankaccount', 'BankAccountTypedDict'), + 'ClientRateLimitWebhook': ('codat_sync_for_expenses.models.shared.clientratelimitwebhook', 'ClientRateLimitWebhook'), + 'ClientRateLimitWebhookPayload': ('codat_sync_for_expenses.models.shared.clientratelimitwebhookpayload', 'ClientRateLimitWebhookPayload'), + 'ClientRateLimitWebhookPayloadTypedDict': ('codat_sync_for_expenses.models.shared.clientratelimitwebhookpayload', 'ClientRateLimitWebhookPayloadTypedDict'), + 'ClientRateLimitWebhookTypedDict': ('codat_sync_for_expenses.models.shared.clientratelimitwebhook', 'ClientRateLimitWebhookTypedDict'), + 'CodatFile': ('codat_sync_for_expenses.models.shared.codatfile', 'CodatFile'), + 'CodatFileTypedDict': ('codat_sync_for_expenses.models.shared.codatfile', 'CodatFileTypedDict'), + 'Companies': ('codat_sync_for_expenses.models.shared.companies', 'Companies'), + 'CompaniesTypedDict': ('codat_sync_for_expenses.models.shared.companies', 'CompaniesTypedDict'), + 'Company': ('codat_sync_for_expenses.models.shared.company', 'Company'), + 'CompanyConfiguration': ('codat_sync_for_expenses.models.shared.companyconfiguration', 'CompanyConfiguration'), + 'CompanyConfigurationTypedDict': ('codat_sync_for_expenses.models.shared.companyconfiguration', 'CompanyConfigurationTypedDict'), + 'CompanyDetails': ('codat_sync_for_expenses.models.company_details', 'CompanyDetails'), + 'CompanyDetailsTypedDict': ('codat_sync_for_expenses.models.company_details', 'CompanyDetailsTypedDict'), + 'CompanyInformation': ('codat_sync_for_expenses.models.company_information', 'CompanyInformation'), + 'CompanyInformationSchemasType': ('codat_sync_for_expenses.models.shared.companyinformation', 'CompanyInformationSchemasType'), + 'CompanyInformationType': ('codat_sync_for_expenses.models.company_information_type', 'CompanyInformationType'), + 'CompanyInformationTypedDict': ('codat_sync_for_expenses.models.company_information', 'CompanyInformationTypedDict'), + 'CompanyReference': ('codat_sync_for_expenses.models.shared.companyreference', 'CompanyReference'), + 'CompanyReferenceLinks': ('codat_sync_for_expenses.models.company_reference_links', 'CompanyReferenceLinks'), + 'CompanyReferenceLinksTypedDict': ('codat_sync_for_expenses.models.company_reference_links', 'CompanyReferenceLinksTypedDict'), + 'CompanyReferenceTypedDict': ('codat_sync_for_expenses.models.shared.companyreference', 'CompanyReferenceTypedDict'), + 'CompanyRequestBody': ('codat_sync_for_expenses.models.shared.companyrequestbody', 'CompanyRequestBody'), + 'CompanyRequestBodyTypedDict': ('codat_sync_for_expenses.models.shared.companyrequestbody', 'CompanyRequestBodyTypedDict'), + 'CompanySyncStatus': ('codat_sync_for_expenses.models.shared.companysyncstatus', 'CompanySyncStatus'), + 'CompanySyncStatusTypedDict': ('codat_sync_for_expenses.models.shared.companysyncstatus', 'CompanySyncStatusTypedDict'), + 'CompanyTypedDict': ('codat_sync_for_expenses.models.shared.company', 'CompanyTypedDict'), + 'CompanyUpdateRequest': ('codat_sync_for_expenses.models.shared.companyupdaterequest', 'CompanyUpdateRequest'), + 'CompanyUpdateRequestTypedDict': ('codat_sync_for_expenses.models.shared.companyupdaterequest', 'CompanyUpdateRequestTypedDict'), + 'Connection': ('codat_sync_for_expenses.models.shared.connection', 'Connection'), + 'ConnectionTypedDict': ('codat_sync_for_expenses.models.shared.connection', 'ConnectionTypedDict'), + 'Connections': ('codat_sync_for_expenses.models.shared.connections', 'Connections'), + 'ConnectionsTypedDict': ('codat_sync_for_expenses.models.shared.connections', 'ConnectionsTypedDict'), + 'Contact': ('codat_sync_for_expenses.models.shared.contact', 'Contact'), + 'ContactTypedDict': ('codat_sync_for_expenses.models.shared.contact', 'ContactTypedDict'), + 'CreateAccountResponse': ('codat_sync_for_expenses.models.shared.createaccountresponse', 'CreateAccountResponse'), + 'CreateAccountResponseAllOfData': ('codat_sync_for_expenses.models.create_account_response_all_of_data', 'CreateAccountResponseAllOfData'), + 'CreateAccountResponseAllOfDataTypedDict': ('codat_sync_for_expenses.models.create_account_response_all_of_data', 'CreateAccountResponseAllOfDataTypedDict'), + 'CreateAccountResponseMetadata': ('codat_sync_for_expenses.models.shared.metadata', 'Metadata'), + 'CreateAccountResponseMetadataTypedDict': ('codat_sync_for_expenses.models.shared.metadata', 'MetadataTypedDict'), + 'CreateAccountResponseTypedDict': ('codat_sync_for_expenses.models.shared.createaccountresponse', 'CreateAccountResponseTypedDict'), + 'CreateAccountResponseValidDataTypeLinks': ('codat_sync_for_expenses.models.valid_data_type_links', 'ValidDataTypeLinks'), + 'CreateAccountResponseValidDataTypeLinksTypedDict': ('codat_sync_for_expenses.models.valid_data_type_links', 'ValidDataTypeLinksTypedDict'), + 'CreateBankAccountResponse': ('codat_sync_for_expenses.models.create_bank_account_response', 'CreateBankAccountResponse'), + 'CreateBankAccountResponseAllOfData': ('codat_sync_for_expenses.models.create_bank_account_response_all_of_data', 'CreateBankAccountResponseAllOfData'), + 'CreateBankAccountResponseAllOfDataTypedDict': ('codat_sync_for_expenses.models.create_bank_account_response_all_of_data', 'CreateBankAccountResponseAllOfDataTypedDict'), + 'CreateBankAccountResponseBankAccountType': ('codat_sync_for_expenses.models.shared.createbankaccountresponse', 'CreateBankAccountResponseBankAccountType'), + 'CreateBankAccountResponseTypedDict': ('codat_sync_for_expenses.models.create_bank_account_response', 'CreateBankAccountResponseTypedDict'), + 'CreateConnectionRequest': ('codat_sync_for_expenses.models.create_connection_request', 'CreateConnectionRequest'), + 'CreateConnectionRequestTypedDict': ('codat_sync_for_expenses.models.create_connection_request', 'CreateConnectionRequestTypedDict'), + 'CreateCustomerResponse': ('codat_sync_for_expenses.models.shared.createcustomerresponse', 'CreateCustomerResponse'), + 'CreateCustomerResponseAllOfData': ('codat_sync_for_expenses.models.create_customer_response_all_of_data', 'CreateCustomerResponseAllOfData'), + 'CreateCustomerResponseAllOfDataTypedDict': ('codat_sync_for_expenses.models.create_customer_response_all_of_data', 'CreateCustomerResponseAllOfDataTypedDict'), + 'CreateCustomerResponseTypedDict': ('codat_sync_for_expenses.models.shared.createcustomerresponse', 'CreateCustomerResponseTypedDict'), + 'CreateExpenseResponse': ('codat_sync_for_expenses.models.shared.createexpenseresponse', 'CreateExpenseResponse'), + 'CreateExpenseResponseTypedDict': ('codat_sync_for_expenses.models.shared.createexpenseresponse', 'CreateExpenseResponseTypedDict'), + 'CreateReimbursableExpenseResponse': ('codat_sync_for_expenses.models.shared.createreimbursableexpenseresponse', 'CreateReimbursableExpenseResponse'), + 'CreateReimbursableExpenseResponseTypedDict': ('codat_sync_for_expenses.models.shared.createreimbursableexpenseresponse', 'CreateReimbursableExpenseResponseTypedDict'), + 'CreateSupplierResponse': ('codat_sync_for_expenses.models.shared.createsupplierresponse', 'CreateSupplierResponse'), + 'CreateSupplierResponseAllOfData': ('codat_sync_for_expenses.models.create_supplier_response_all_of_data', 'CreateSupplierResponseAllOfData'), + 'CreateSupplierResponseAllOfDataTypedDict': ('codat_sync_for_expenses.models.create_supplier_response_all_of_data', 'CreateSupplierResponseAllOfDataTypedDict'), + 'CreateSupplierResponseTypedDict': ('codat_sync_for_expenses.models.shared.createsupplierresponse', 'CreateSupplierResponseTypedDict'), + 'CurrentStatus': ('codat_sync_for_expenses.models.current_status', 'CurrentStatus'), + 'Customer': ('codat_sync_for_expenses.models.shared.customer', 'Customer'), + 'CustomerDetails': ('codat_sync_for_expenses.models.shared.customerdetails', 'CustomerDetails'), + 'CustomerDetailsTypedDict': ('codat_sync_for_expenses.models.shared.customerdetails', 'CustomerDetailsTypedDict'), + 'CustomerStatus': ('codat_sync_for_expenses.models.shared.customerstatus', 'CustomerStatus'), + 'CustomerTypedDict': ('codat_sync_for_expenses.models.shared.customer', 'CustomerTypedDict'), + 'Customers': ('codat_sync_for_expenses.models.shared.customers', 'Customers'), + 'CustomersTypedDict': ('codat_sync_for_expenses.models.shared.customers', 'CustomersTypedDict'), + 'DataConnectionError': ('codat_sync_for_expenses.models.shared.dataconnectionerror', 'DataConnectionError'), + 'DataConnectionErrorTypedDict': ('codat_sync_for_expenses.models.shared.dataconnectionerror', 'DataConnectionErrorTypedDict'), + 'DataConnectionStatus': ('codat_sync_for_expenses.models.shared.dataconnectionstatus', 'DataConnectionStatus'), + 'DataStatus': ('codat_sync_for_expenses.models.shared.datastatus', 'DataStatus'), + 'DataStatusTypedDict': ('codat_sync_for_expenses.models.shared.datastatus', 'DataStatusTypedDict'), + 'DataStatuses': ('codat_sync_for_expenses.models.data_statuses', 'DataStatuses'), + 'DataStatusesTypedDict': ('codat_sync_for_expenses.models.data_statuses', 'DataStatusesTypedDict'), + 'DataType': ('codat_sync_for_expenses.models.shared.datatype', 'DataType'), + 'DataTypes': ('codat_sync_for_expenses.models.data_types', 'DataTypes'), + 'DatasetStatus': ('codat_sync_for_expenses.models.dataset_status', 'DatasetStatus'), + 'ErrorMessage': ('codat_sync_for_expenses.models.error_message', 'ErrorMessage'), + 'ErrorMessageTypedDict': ('codat_sync_for_expenses.models.error_message', 'ErrorMessageTypedDict'), + 'ErrorStatus': ('codat_sync_for_expenses.models.error_status', 'ErrorStatus'), + 'ErrorValidation': ('codat_sync_for_expenses.models.shared.errorvalidation', 'ErrorValidation'), + 'ErrorValidationItem': ('codat_sync_for_expenses.models.shared.errorvalidationitem', 'ErrorValidationItem'), + 'ErrorValidationItemTypedDict': ('codat_sync_for_expenses.models.shared.errorvalidationitem', 'ErrorValidationItemTypedDict'), + 'ErrorValidationTypedDict': ('codat_sync_for_expenses.models.shared.errorvalidation', 'ErrorValidationTypedDict'), + 'ExpenseContactRef': ('codat_sync_for_expenses.models.expense_contact_ref', 'ExpenseContactRef'), + 'ExpenseContactRefType': ('codat_sync_for_expenses.models.shared.expensecontactref', 'ExpenseContactRefType'), + 'ExpenseContactRefTypedDict': ('codat_sync_for_expenses.models.expense_contact_ref', 'ExpenseContactRefTypedDict'), + 'ExpenseTransaction': ('codat_sync_for_expenses.models.shared.expensetransaction', 'ExpenseTransaction'), + 'ExpenseTransactionLine': ('codat_sync_for_expenses.models.shared.expensetransactionline', 'ExpenseTransactionLine'), + 'ExpenseTransactionLineTypedDict': ('codat_sync_for_expenses.models.shared.expensetransactionline', 'ExpenseTransactionLineTypedDict'), + 'ExpenseTransactionType': ('codat_sync_for_expenses.models.expense_transaction_type', 'ExpenseTransactionType'), + 'ExpenseTransactionTypedDict': ('codat_sync_for_expenses.models.shared.expensetransaction', 'ExpenseTransactionTypedDict'), + 'ExpensesSyncWebhook': ('codat_sync_for_expenses.models.shared.expensessyncwebhook', 'ExpensesSyncWebhook'), + 'ExpensesSyncWebhookPayload': ('codat_sync_for_expenses.models.shared.expensessyncwebhookpayload', 'ExpensesSyncWebhookPayload'), + 'ExpensesSyncWebhookPayloadTypedDict': ('codat_sync_for_expenses.models.shared.expensessyncwebhookpayload', 'ExpensesSyncWebhookPayloadTypedDict'), + 'ExpensesSyncWebhookStatus': ('codat_sync_for_expenses.models.expenses_sync_webhook_status', 'ExpensesSyncWebhookStatus'), + 'ExpensesSyncWebhookTypedDict': ('codat_sync_for_expenses.models.shared.expensessyncwebhook', 'ExpensesSyncWebhookTypedDict'), + 'From': ('codat_sync_for_expenses.models.transfer_transaction_request_from', 'TransferTransactionRequestFrom'), + 'FromTypedDict': ('codat_sync_for_expenses.models.transfer_transaction_request_from', 'TransferTransactionRequestFromTypedDict'), + 'HalRef': ('codat_sync_for_expenses.models.shared.halref', 'HalRef'), + 'HalRefTypedDict': ('codat_sync_for_expenses.models.shared.halref', 'HalRefTypedDict'), + 'IntegrationType': ('codat_sync_for_expenses.models.shared.integrationtype', 'IntegrationType'), + 'InvoiceTo': ('codat_sync_for_expenses.models.shared.invoiceto', 'InvoiceTo'), + 'InvoiceToType': ('codat_sync_for_expenses.models.invoice_to_type', 'InvoiceToType'), + 'InvoiceToTypedDict': ('codat_sync_for_expenses.models.shared.invoiceto', 'InvoiceToTypedDict'), + 'ItemRef': ('codat_sync_for_expenses.models.shared.itemref', 'ItemRef'), + 'ItemRefTypedDict': ('codat_sync_for_expenses.models.shared.itemref', 'ItemRefTypedDict'), + 'Items': ('codat_sync_for_expenses.models.shared.items', 'Items'), + 'ItemsTypedDict': ('codat_sync_for_expenses.models.shared.items', 'ItemsTypedDict'), + 'Links': ('codat_sync_for_expenses.models.shared.links', 'Links'), + 'LinksTypedDict': ('codat_sync_for_expenses.models.shared.links', 'LinksTypedDict'), + 'MappingOptions': ('codat_sync_for_expenses.models.shared.mappingoptions', 'MappingOptions'), + 'MappingOptionsTypedDict': ('codat_sync_for_expenses.models.shared.mappingoptions', 'MappingOptionsTypedDict'), + 'Metadata': ('codat_sync_for_expenses.models.shared.metadata', 'Metadata'), + 'MetadataTypedDict': ('codat_sync_for_expenses.models.shared.metadata', 'MetadataTypedDict'), + 'Model3': ('codat_sync_for_expenses.models.model3', 'Model3'), + 'Model3TypedDict': ('codat_sync_for_expenses.models.model3', 'Model3TypedDict'), + 'PagingInfo': ('codat_sync_for_expenses.models.paging_info', 'PagingInfo'), + 'PagingInfoTypedDict': ('codat_sync_for_expenses.models.paging_info', 'PagingInfoTypedDict'), + 'Phone': ('codat_sync_for_expenses.models.shared.phonenumber_items', 'PhoneNumberItems'), + 'PhoneNumberItems': ('codat_sync_for_expenses.models.shared.phonenumber_items', 'PhoneNumberItems'), + 'PhoneNumberItemsType': ('codat_sync_for_expenses.models.phone_number_items_type', 'PhoneNumberItemsType'), + 'PhoneNumberItemsTypedDict': ('codat_sync_for_expenses.models.shared.phonenumber_items', 'PhoneNumberItemsTypedDict'), + 'PhoneTypedDict': ('codat_sync_for_expenses.models.shared.phonenumber_items', 'PhoneNumberItemsTypedDict'), + 'PullOperation': ('codat_sync_for_expenses.models.shared.pulloperation', 'PullOperation'), + 'PullOperationTypedDict': ('codat_sync_for_expenses.models.shared.pulloperation', 'PullOperationTypedDict'), + 'PullOperations': ('codat_sync_for_expenses.models.shared.pulloperations', 'PullOperations'), + 'PullOperationsTypedDict': ('codat_sync_for_expenses.models.shared.pulloperations', 'PullOperationsTypedDict'), + 'PushChangeType': ('codat_sync_for_expenses.models.shared.pushchangetype', 'PushChangeType'), + 'PushFieldValidation': ('codat_sync_for_expenses.models.shared.pushfieldvalidation', 'PushFieldValidation'), + 'PushFieldValidationTypedDict': ('codat_sync_for_expenses.models.shared.pushfieldvalidation', 'PushFieldValidationTypedDict'), + 'PushOperation': ('codat_sync_for_expenses.models.shared.pushoperation', 'PushOperation'), + 'PushOperationChange': ('codat_sync_for_expenses.models.shared.pushoperationchange', 'PushOperationChange'), + 'PushOperationChangeTypedDict': ('codat_sync_for_expenses.models.shared.pushoperationchange', 'PushOperationChangeTypedDict'), + 'PushOperationRef': ('codat_sync_for_expenses.models.shared.pushoperationref', 'PushOperationRef'), + 'PushOperationRefTypedDict': ('codat_sync_for_expenses.models.shared.pushoperationref', 'PushOperationRefTypedDict'), + 'PushOperationStatus': ('codat_sync_for_expenses.models.shared.pushoperationstatus', 'PushOperationStatus'), + 'PushOperationTypedDict': ('codat_sync_for_expenses.models.shared.pushoperation', 'PushOperationTypedDict'), + 'PushOperations': ('codat_sync_for_expenses.models.shared.pushoperations', 'PushOperations'), + 'PushOperationsTypedDict': ('codat_sync_for_expenses.models.shared.pushoperations', 'PushOperationsTypedDict'), + 'PushOption': ('codat_sync_for_expenses.models.shared.pushoption', 'PushOption'), + 'PushOptionChoice': ('codat_sync_for_expenses.models.shared.pushoptionchoice', 'PushOptionChoice'), + 'PushOptionChoiceTypedDict': ('codat_sync_for_expenses.models.shared.pushoptionchoice', 'PushOptionChoiceTypedDict'), + 'PushOptionProperty': ('codat_sync_for_expenses.models.shared.pushoptionproperty', 'PushOptionProperty'), + 'PushOptionPropertyTypedDict': ('codat_sync_for_expenses.models.shared.pushoptionproperty', 'PushOptionPropertyTypedDict'), + 'PushOptionType': ('codat_sync_for_expenses.models.shared.pushoptiontype', 'PushOptionType'), + 'PushOptionTypedDict': ('codat_sync_for_expenses.models.shared.pushoption', 'PushOptionTypedDict'), + 'PushValidationInfo': ('codat_sync_for_expenses.models.shared.pushvalidationinfo', 'PushValidationInfo'), + 'PushValidationInfoTypedDict': ('codat_sync_for_expenses.models.shared.pushvalidationinfo', 'PushValidationInfoTypedDict'), + 'RecordRef': ('codat_sync_for_expenses.models.shared.recordref', 'RecordRef'), + 'RecordRefTypedDict': ('codat_sync_for_expenses.models.shared.recordref', 'RecordRefTypedDict'), + 'ReimbursableExpenseTransaction': ('codat_sync_for_expenses.models.shared.reimbursableexpensetransaction', 'ReimbursableExpenseTransaction'), + 'ReimbursableExpenseTransactionLine': ('codat_sync_for_expenses.models.shared.reimbursableexpensetransactionline', 'ReimbursableExpenseTransactionLine'), + 'ReimbursableExpenseTransactionLineTypedDict': ('codat_sync_for_expenses.models.shared.reimbursableexpensetransactionline', 'ReimbursableExpenseTransactionLineTypedDict'), + 'ReimbursableExpenseTransactionTypedDict': ('codat_sync_for_expenses.models.shared.reimbursableexpensetransaction', 'ReimbursableExpenseTransactionTypedDict'), + 'ReimbursementContactRef': ('codat_sync_for_expenses.models.shared.reimbursementcontactref', 'ReimbursementContactRef'), + 'ReimbursementContactRefTypedDict': ('codat_sync_for_expenses.models.shared.reimbursementcontactref', 'ReimbursementContactRefTypedDict'), + 'SchemaDataType': ('codat_sync_for_expenses.models.shared.schema_datatype', 'SchemaDataType'), + 'SchemaTransaction': ('codat_sync_for_expenses.models.shared.schema_transaction', 'SchemaTransaction'), + 'SchemaTransactionTypedDict': ('codat_sync_for_expenses.models.shared.schema_transaction', 'SchemaTransactionTypedDict'), + 'Security': ('codat_sync_for_expenses.models.shared.security', 'Security'), + 'SecurityTypedDict': ('codat_sync_for_expenses.models.shared.security', 'SecurityTypedDict'), + 'SourceType': ('codat_sync_for_expenses.models.source_type', 'SourceType'), + 'Status': ('codat_sync_for_expenses.models.shared.status', 'Status'), + 'SupplementalData': ('codat_sync_for_expenses.models.shared.supplementaldata', 'SupplementalData'), + 'SupplementalDataTypedDict': ('codat_sync_for_expenses.models.shared.supplementaldata', 'SupplementalDataTypedDict'), + 'Supplier': ('codat_sync_for_expenses.models.shared.supplier', 'Supplier'), + 'SupplierDetails': ('codat_sync_for_expenses.models.shared.supplierdetails', 'SupplierDetails'), + 'SupplierDetailsTypedDict': ('codat_sync_for_expenses.models.shared.supplierdetails', 'SupplierDetailsTypedDict'), + 'SupplierStatus': ('codat_sync_for_expenses.models.shared.supplierstatus', 'SupplierStatus'), + 'SupplierTypedDict': ('codat_sync_for_expenses.models.shared.supplier', 'SupplierTypedDict'), + 'Suppliers': ('codat_sync_for_expenses.models.shared.suppliers', 'Suppliers'), + 'SuppliersTypedDict': ('codat_sync_for_expenses.models.shared.suppliers', 'SuppliersTypedDict'), + 'SyncCompleteWebhook': ('codat_sync_for_expenses.models.sync_complete_webhook', 'SyncCompleteWebhook'), + 'SyncCompleteWebhookData': ('codat_sync_for_expenses.models.sync_complete_webhook_data', 'SyncCompleteWebhookData'), + 'SyncCompleteWebhookDataTypedDict': ('codat_sync_for_expenses.models.sync_complete_webhook_data', 'SyncCompleteWebhookDataTypedDict'), + 'SyncCompleteWebhookTypedDict': ('codat_sync_for_expenses.models.sync_complete_webhook', 'SyncCompleteWebhookTypedDict'), + 'SyncFailedWebhook': ('codat_sync_for_expenses.models.sync_failed_webhook', 'SyncFailedWebhook'), + 'SyncFailedWebhookData': ('codat_sync_for_expenses.models.sync_failed_webhook_data', 'SyncFailedWebhookData'), + 'SyncFailedWebhookDataTypedDict': ('codat_sync_for_expenses.models.sync_failed_webhook_data', 'SyncFailedWebhookDataTypedDict'), + 'SyncFailedWebhookTypedDict': ('codat_sync_for_expenses.models.sync_failed_webhook', 'SyncFailedWebhookTypedDict'), + 'SyncInitiated': ('codat_sync_for_expenses.models.sync_initiated', 'SyncInitiated'), + 'SyncInitiatedTypedDict': ('codat_sync_for_expenses.models.sync_initiated', 'SyncInitiatedTypedDict'), + 'TaxRateMappingInfo': ('codat_sync_for_expenses.models.shared.taxratemappinginfo', 'TaxRateMappingInfo'), + 'TaxRateMappingInfoTypedDict': ('codat_sync_for_expenses.models.shared.taxratemappinginfo', 'TaxRateMappingInfoTypedDict'), + 'To': ('codat_sync_for_expenses.models.transfer_transaction_request_to', 'TransferTransactionRequestTo'), + 'ToTypedDict': ('codat_sync_for_expenses.models.transfer_transaction_request_to', 'TransferTransactionRequestToTypedDict'), + 'TrackingCategoryMappingInfo': ('codat_sync_for_expenses.models.shared.trackingcategorymappinginfo', 'TrackingCategoryMappingInfo'), + 'TrackingCategoryMappingInfoTypedDict': ('codat_sync_for_expenses.models.shared.trackingcategorymappinginfo', 'TrackingCategoryMappingInfoTypedDict'), + 'TrackingRef': ('codat_sync_for_expenses.models.shared.trackingref', 'TrackingRef'), + 'TrackingRefAdjustmentTransaction': ('codat_sync_for_expenses.models.shared.trackingrefadjustmenttransaction', 'TrackingRefAdjustmentTransaction'), + 'TrackingRefAdjustmentTransactionDataType': ('codat_sync_for_expenses.models.tracking_ref_adjustment_transaction_data_type', 'TrackingRefAdjustmentTransactionDataType'), + 'TrackingRefAdjustmentTransactionTypedDict': ('codat_sync_for_expenses.models.shared.trackingrefadjustmenttransaction', 'TrackingRefAdjustmentTransactionTypedDict'), + 'TrackingRefDataType': ('codat_sync_for_expenses.models.tracking_ref_data_type', 'TrackingRefDataType'), + 'TrackingRefTypedDict': ('codat_sync_for_expenses.models.shared.trackingref', 'TrackingRefTypedDict'), + 'Transaction': ('codat_sync_for_expenses.models.transaction', 'Transaction'), + 'TransactionDefinitionsStatus': ('codat_sync_for_expenses.models.shared.transaction', 'TransactionDefinitionsStatus'), + 'TransactionStatus': ('codat_sync_for_expenses.models.shared.transactionstatus', 'TransactionStatus'), + 'TransactionTypedDict': ('codat_sync_for_expenses.models.transaction', 'TransactionTypedDict'), + 'Transactions': ('codat_sync_for_expenses.models.shared.transactions', 'Transactions'), + 'TransactionsTypedDict': ('codat_sync_for_expenses.models.shared.transactions', 'TransactionsTypedDict'), + 'TransferTransactionRequest': ('codat_sync_for_expenses.models.shared.transfertransactionrequest', 'TransferTransactionRequest'), + 'TransferTransactionRequestAccountReference': ('codat_sync_for_expenses.models.account_reference', 'AccountReference'), + 'TransferTransactionRequestAccountReferenceTypedDict': ('codat_sync_for_expenses.models.account_reference', 'AccountReferenceTypedDict'), + 'TransferTransactionRequestFrom': ('codat_sync_for_expenses.models.transfer_transaction_request_from', 'TransferTransactionRequestFrom'), + 'TransferTransactionRequestFromTypedDict': ('codat_sync_for_expenses.models.transfer_transaction_request_from', 'TransferTransactionRequestFromTypedDict'), + 'TransferTransactionRequestTo': ('codat_sync_for_expenses.models.transfer_transaction_request_to', 'TransferTransactionRequestTo'), + 'TransferTransactionRequestToTypedDict': ('codat_sync_for_expenses.models.transfer_transaction_request_to', 'TransferTransactionRequestToTypedDict'), + 'TransferTransactionRequestTypedDict': ('codat_sync_for_expenses.models.shared.transfertransactionrequest', 'TransferTransactionRequestTypedDict'), + 'TransferTransactionResponse': ('codat_sync_for_expenses.models.shared.transfertransactionresponse', 'TransferTransactionResponse'), + 'TransferTransactionResponseTypedDict': ('codat_sync_for_expenses.models.shared.transfertransactionresponse', 'TransferTransactionResponseTypedDict'), + 'Type': ('codat_sync_for_expenses.models.type', 'Type'), + 'UpdateConnection': ('codat_sync_for_expenses.models.update_connection', 'UpdateConnection'), + 'UpdateConnectionTypedDict': ('codat_sync_for_expenses.models.update_connection', 'UpdateConnectionTypedDict'), + 'UpdateCustomerResponse': ('codat_sync_for_expenses.models.shared.updatecustomerresponse', 'UpdateCustomerResponse'), + 'UpdateCustomerResponseAccountingCustomer': ('codat_sync_for_expenses.models.update_customer_response_all_of_data', 'UpdateCustomerResponseAllOfData'), + 'UpdateCustomerResponseAccountingCustomerTypedDict': ('codat_sync_for_expenses.models.update_customer_response_all_of_data', 'UpdateCustomerResponseAllOfData'), + 'UpdateCustomerResponseAllOfData': ('codat_sync_for_expenses.models.update_customer_response_all_of_data', 'UpdateCustomerResponseAllOfData'), + 'UpdateCustomerResponseAllOfDataTypedDict': ('codat_sync_for_expenses.models.update_customer_response_all_of_data', 'UpdateCustomerResponseAllOfDataTypedDict'), + 'UpdateCustomerResponseTypedDict': ('codat_sync_for_expenses.models.shared.updatecustomerresponse', 'UpdateCustomerResponseTypedDict'), + 'UpdateExpenseRequest': ('codat_sync_for_expenses.models.shared.updateexpenserequest', 'UpdateExpenseRequest'), + 'UpdateExpenseRequestBankAccountReference': ('codat_sync_for_expenses.models.bank_account_reference', 'BankAccountReference'), + 'UpdateExpenseRequestBankAccountReferenceTypedDict': ('codat_sync_for_expenses.models.bank_account_reference', 'BankAccountReferenceTypedDict'), + 'UpdateExpenseRequestType': ('codat_sync_for_expenses.models.update_expense_request_type', 'UpdateExpenseRequestType'), + 'UpdateExpenseRequestTypedDict': ('codat_sync_for_expenses.models.shared.updateexpenserequest', 'UpdateExpenseRequestTypedDict'), + 'UpdateExpenseResponse': ('codat_sync_for_expenses.models.shared.updateexpenseresponse', 'UpdateExpenseResponse'), + 'UpdateExpenseResponseTypedDict': ('codat_sync_for_expenses.models.shared.updateexpenseresponse', 'UpdateExpenseResponseTypedDict'), + 'UpdateReimbursableExpenseTransactionRequest': ('codat_sync_for_expenses.models.shared.updatereimbursableexpensetransactionrequest', 'UpdateReimbursableExpenseTransactionRequest'), + 'UpdateReimbursableExpenseTransactionRequestTypedDict': ('codat_sync_for_expenses.models.shared.updatereimbursableexpensetransactionrequest', 'UpdateReimbursableExpenseTransactionRequestTypedDict'), + 'UpdateSupplierResponse': ('codat_sync_for_expenses.models.shared.updatesupplierresponse', 'UpdateSupplierResponse'), + 'UpdateSupplierResponseAccountingSupplier': ('codat_sync_for_expenses.models.update_supplier_response_all_of_data', 'UpdateSupplierResponseAllOfData'), + 'UpdateSupplierResponseAccountingSupplierTypedDict': ('codat_sync_for_expenses.models.update_supplier_response_all_of_data', 'UpdateSupplierResponseAllOfData'), + 'UpdateSupplierResponseAllOfData': ('codat_sync_for_expenses.models.update_supplier_response_all_of_data', 'UpdateSupplierResponseAllOfData'), + 'UpdateSupplierResponseAllOfDataTypedDict': ('codat_sync_for_expenses.models.update_supplier_response_all_of_data', 'UpdateSupplierResponseAllOfDataTypedDict'), + 'UpdateSupplierResponseTypedDict': ('codat_sync_for_expenses.models.shared.updatesupplierresponse', 'UpdateSupplierResponseTypedDict'), + 'ValidDataTypeLinks': ('codat_sync_for_expenses.models.valid_data_type_links', 'ValidDataTypeLinks'), + 'ValidDataTypeLinksTypedDict': ('codat_sync_for_expenses.models.valid_data_type_links', 'ValidDataTypeLinksTypedDict'), + 'ValidFor': ('codat_sync_for_expenses.models.shared.validfor', 'ValidFor'), + 'ValidTransactionTypes': ('codat_sync_for_expenses.models.shared.validtransactiontypes', 'ValidTransactionTypes'), + 'Validation': ('codat_sync_for_expenses.models.shared.validation', 'Validation'), + 'ValidationItem': ('codat_sync_for_expenses.models.shared.validationitem', 'ValidationItem'), + 'ValidationItemTypedDict': ('codat_sync_for_expenses.models.shared.validationitem', 'ValidationItemTypedDict'), + 'ValidationTypedDict': ('codat_sync_for_expenses.models.shared.validation', 'ValidationTypedDict'), + 'Weblink': ('codat_sync_for_expenses.models.weblink', 'Weblink'), + 'WeblinkTypedDict': ('codat_sync_for_expenses.models.weblink', 'WeblinkTypedDict'), } -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-expenses/src/codat_sync_for_expenses/models/shared/accountingaddresstype.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/accountingaddresstype.py index 4d5a97871..ef15d3b74 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/accountingaddresstype.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/accountingaddresstype.py @@ -1,12 +1,39 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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 AccountingAddressType(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 AccountingAddressType from a JSON string""" + return cls(json.loads(json_str)) + - UNKNOWN = "Unknown" - BILLING = "Billing" - DELIVERY = "Delivery" diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/accountmappinginfo.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/accountmappinginfo.py index c9d996c16..50c89ffd1 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/accountmappinginfo.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/accountmappinginfo.py @@ -1,133 +1,177 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .validfor import ValidFor -from .validtransactiontypes import ValidTransactionTypes -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from enum import Enum -import pydantic -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class AccountMappingInfoAccountType(str, Enum): - r"""Type of the account.""" - - ASSET = "Asset" - LIABILITY = "Liability" - INCOME = "Income" - EXPENSE = "Expense" - EQUITY = "Equity" +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class AccountMappingInfoTypedDict(TypedDict): - account_type: NotRequired[AccountMappingInfoAccountType] - r"""Type of the account.""" - currency: NotRequired[str] - r"""Currency of the account.""" - fully_qualified_category: NotRequired[str] - r"""Full account type and category of the account""" - id: NotRequired[str] - r"""Unique identifier of account.""" - is_bank_account: NotRequired[bool] - r"""Confirms whether the account is a bank account or not.""" - name: NotRequired[str] - r"""Name of the account as it appears in the company's accounting software.""" - nominal_code: NotRequired[Nullable[str]] - r"""Code used to identify each nominal account in the accounting software.""" - valid_for: NotRequired[List[ValidFor]] - r"""Supported endpoints for the account.""" - valid_transaction_types: NotRequired[List[ValidTransactionTypes]] - r"""Supported transaction types for the account.""" + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.models.shared.validfor import ValidFor +from codat_sync_for_expenses.models.shared.validtransactiontypes import ValidTransactionTypes +from codat_sync_for_expenses.models.account_mapping_info_account_type import AccountMappingInfoAccountType +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_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL class AccountMappingInfo(BaseModel): - account_type: Annotated[ - Optional[AccountMappingInfoAccountType], pydantic.Field(alias="accountType") - ] = None - r"""Type of the account.""" - currency: Optional[str] = None - r"""Currency of the account.""" + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'nominalCode', 'nominal_code'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + AccountMappingInfo + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Unique identifier of account.") + nominal_code: OptionalNullable[str] = Field(default=UNSET, description="Code used to identify each nominal account in the accounting software.", alias="nominalCode") + name: Optional[str] = Field(default=None, description="Name of the account as it appears in the company's accounting software.") + currency: Optional[str] = Field(default=None, description="Currency of the account.") + account_type: Optional[AccountMappingInfoAccountType] = Field(default=None, description="Type of the account.", alias="accountType") + fully_qualified_category: Optional[str] = Field(default=None, description="Full account type and category of the account", alias="fullyQualifiedCategory") + is_bank_account: Optional[bool] = Field(default=None, description="Confirms whether the account is a bank account or not.", alias="isBankAccount") + valid_transaction_types: Optional[List[ValidTransactionTypes]] = Field(default=None, description="Supported transaction types for the account.", alias="validTransactionTypes") + valid_for: Optional[List[ValidFor]] = Field(default=None, description="Supported endpoints for the account.", alias="validFor") + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["id", "nominalCode", "name", "currency", "accountType", "fullyQualifiedCategory", "isBankAccount", "validTransactionTypes", "validFor"] + + @field_validator('account_type') + def account_type_validate_enum(cls, value): + """Validates the enum""" + if value is None: + return value + + if value not in set(['Asset', 'Liability', 'Income', 'Expense', 'Equity']): + raise ValueError("must be one of enum values ('Asset', 'Liability', 'Income', 'Expense', 'Equity')") + return value + + @field_validator('valid_transaction_types') + def valid_transaction_types_validate_enum(cls, value): + """Validates the enum""" + if value is None: + return value + + for i in value: + if i not in set(['Payment', 'Refund', 'Reward', 'Chargeback']): + raise ValueError("each list item must be one of ('Payment', 'Refund', 'Reward', 'Chargeback')") + return value + + @field_validator('valid_for') + def valid_for_validate_enum(cls, value): + """Validates the enum""" + if value is None: + return value + + for i in value: + if i not in set(['expense-transactions.Payment', 'expense-transactions.Refund', 'expense-transactions.Reward', 'expense-transactions.Chargeback', 'reimbursable-expense-transactions', 'transfer-transactions', 'adjustment-transactions']): + raise ValueError("each list item must be one of ('expense-transactions.Payment', 'expense-transactions.Refund', 'expense-transactions.Reward', 'expense-transactions.Chargeback', 'reimbursable-expense-transactions', 'transfer-transactions', 'adjustment-transactions')") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) - fully_qualified_category: Annotated[ - Optional[str], pydantic.Field(alias="fullyQualifiedCategory") - ] = None - r"""Full account type and category of the account""" - id: Optional[str] = None - r"""Unique identifier of account.""" + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - is_bank_account: Annotated[ - Optional[bool], pydantic.Field(alias="isBankAccount") - ] = None - r"""Confirms whether the account is a bank account or not.""" + 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()) - name: Optional[str] = None - r"""Name of the account as it appears in the company's accounting software.""" + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of AccountMappingInfo from a JSON string""" + return cls.from_dict(json.loads(json_str)) - nominal_code: Annotated[ - OptionalNullable[str], pydantic.Field(alias="nominalCode") - ] = UNSET - r"""Code used to identify each nominal account in the accounting software.""" + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - valid_for: Annotated[Optional[List[ValidFor]], pydantic.Field(alias="validFor")] = ( - None - ) - r"""Supported endpoints for the account.""" + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - valid_transaction_types: Annotated[ - Optional[List[ValidTransactionTypes]], - pydantic.Field(alias="validTransactionTypes"), - ] = None - r"""Supported transaction types for the account.""" + * `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", + ]) - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "accountType", - "currency", - "fullyQualifiedCategory", - "id", - "isBankAccount", - "name", - "nominalCode", - "validFor", - "validTransactionTypes", - ] + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, ) - nullable_fields = set(["nominalCode"]) - 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: - AccountMappingInfo.model_rebuild() -except NameError: - pass + # 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 AccountMappingInfo 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"), + "nominalCode": obj.get("nominalCode"), + "name": obj.get("name"), + "currency": obj.get("currency"), + "accountType": obj.get("accountType"), + "fullyQualifiedCategory": obj.get("fullyQualifiedCategory"), + "isBankAccount": obj.get("isBankAccount"), + "validTransactionTypes": obj.get("validTransactionTypes"), + "validFor": obj.get("validFor") + }) + # 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 AccountMappingInfoTypedDict(TypedDict): + """TypedDict variant of AccountMappingInfo, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + nominal_code: NotRequired[Optional[str]] + name: NotRequired[Optional[str]] + currency: NotRequired[Optional[str]] + account_type: NotRequired[Optional[AccountMappingInfoAccountType]] + fully_qualified_category: NotRequired[Optional[str]] + is_bank_account: NotRequired[Optional[bool]] + valid_transaction_types: NotRequired[Optional[List[ValidTransactionTypes]]] + valid_for: NotRequired[Optional[List[ValidFor]]] + additional_properties: NotRequired[Dict[str, Any]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/accountprototype.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/accountprototype.py index 7e902f173..b0b11aa27 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/accountprototype.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/accountprototype.py @@ -1,320 +1,153 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .accountstatus import AccountStatus -from .accounttype import AccountType -from .supplementaldata import SupplementalData, SupplementalDataTypedDict -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from codat_sync_for_expenses.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 ValidDataTypeLinksTypedDict(TypedDict): - r"""When querying Codat's data model, some data types return `validDatatypeLinks` metadata in the JSON response. This indicates where that object can be used as a reference—a _valid link_—when creating or updating other data. - - For example, `validDatatypeLinks` might indicate the following references: - - - Which tax rates are valid to use on the line item of a bill. - - Which items can be used when creating an invoice. - - You can use `validDatatypeLinks` to present your SMB customers with only valid choices when selecting objects from a list, for example. - - ## `validDatatypeLinks` example - - The following example uses the `Accounting.Accounts` data type. It shows that, on the linked integration, this account is valid as the account on a payment or bill payment; and as the account referenced on the line item of a direct income or direct cost. Because there is no valid link to Invoices or Bills, using this account on those data types will result in an error. - - ```json validDatatypeLinks for an account - { - \"id\": \"bd9e85e0-0478-433d-ae9f-0b3c4f04bfe4\", - \"nominalCode\": \"090\", - \"name\": \"Business Bank Account\", - #... - \"validDatatypeLinks\": [ - { - \"property\": \"Id\", - \"links\": [ - \"Payment.AccountRef.Id\", - \"BillPayment.AccountRef.Id\", - \"DirectIncome.LineItems.AccountRef.Id\", - \"DirectCost.LineItems.AccountRef.Id\" - ] - } - ] - } - ``` - - - - ## Support for `validDatatypeLinks` - - Codat currently supports `validDatatypeLinks` for some data types on our Xero, QuickBooks Online, QuickBooks Desktop, Exact (NL), and Sage Business Cloud integrations. - - If you'd like us to extend support to more data types or integrations, suggest or vote for this on our Product Roadmap. - """ - - links: NotRequired[Nullable[List[str]]] - r"""Supported `dataTypes` that the record can be linked to.""" - property: NotRequired[Nullable[str]] - r"""The property from the account that can be linked.""" - - -class ValidDataTypeLinks(BaseModel): - r"""When querying Codat's data model, some data types return `validDatatypeLinks` metadata in the JSON response. This indicates where that object can be used as a reference—a _valid link_—when creating or updating other data. +""" + Expenses - For example, `validDatatypeLinks` might indicate the following references: + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | - - Which tax rates are valid to use on the line item of a bill. - - Which items can be used when creating an invoice. + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - You can use `validDatatypeLinks` to present your SMB customers with only valid choices when selecting objects from a list, for example. + Do not edit the class manually. +""" # noqa: E501 - ## `validDatatypeLinks` example - The following example uses the `Accounting.Accounts` data type. It shows that, on the linked integration, this account is valid as the account on a payment or bill payment; and as the account referenced on the line item of a direct income or direct cost. Because there is no valid link to Invoices or Bills, using this account on those data types will result in an error. - - ```json validDatatypeLinks for an account - { - \"id\": \"bd9e85e0-0478-433d-ae9f-0b3c4f04bfe4\", - \"nominalCode\": \"090\", - \"name\": \"Business Bank Account\", - #... - \"validDatatypeLinks\": [ - { - \"property\": \"Id\", - \"links\": [ - \"Payment.AccountRef.Id\", - \"BillPayment.AccountRef.Id\", - \"DirectIncome.LineItems.AccountRef.Id\", - \"DirectCost.LineItems.AccountRef.Id\" - ] - } - ] - } - ``` - - - - ## Support for `validDatatypeLinks` - - Codat currently supports `validDatatypeLinks` for some data types on our Xero, QuickBooks Online, QuickBooks Desktop, Exact (NL), and Sage Business Cloud integrations. - - If you'd like us to extend support to more data types or integrations, suggest or vote for this on our Product Roadmap. - """ - - links: OptionalNullable[List[str]] = UNSET - r"""Supported `dataTypes` that the record can be linked to.""" - - property: OptionalNullable[str] = UNSET - r"""The property from the account that can be linked.""" +from __future__ import annotations +from decimal import Decimal +from codat_sync_for_expenses.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_expenses.models.shared.accountstatus import AccountStatus +from codat_sync_for_expenses.models.shared.accounttype import AccountType +from codat_sync_for_expenses.models.shared.supplementaldata import SupplementalData, SupplementalDataTypedDict +from codat_sync_for_expenses.models.valid_data_type_links import ValidDataTypeLinks, ValidDataTypeLinksTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL +class AccountPrototype(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["links", "property"]) - nullable_fields = set(["links", "property"]) + 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 - - -class AccountPrototypeTypedDict(TypedDict): - 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. - """ - current_balance: NotRequired[Nullable[Decimal]] - r"""Current balance in the account.""" - description: NotRequired[Nullable[str]] - r"""Description for the account.""" - fully_qualified_category: NotRequired[Nullable[str]] - r"""Full category of the account. - - For example, `Liability.Current` or `Income.Revenue`. To determine a list of possible categories for each integration, see our examples, follow our [Create, update, delete data](https://docs.codat.io/using-the-api/push) guide, or refer to the integration's own documentation. - """ - fully_qualified_name: NotRequired[Nullable[str]] - r"""Full name of the account, for example: - - `Cash On Hand` - - `Rents Held In Trust` - - `Fixed Asset` - """ - is_bank_account: NotRequired[bool] - r"""Confirms whether the account is a bank account or not.""" - name: NotRequired[Nullable[str]] - r"""Name of the account.""" - 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.""" - status: NotRequired[AccountStatus] - r"""Status of the account""" - supplemental_data: NotRequired[SupplementalDataTypedDict] - r"""Supplemental data is additional data you can include in our standard data types. - - It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. - """ - type: NotRequired[AccountType] - r"""Type of account""" - valid_datatype_links: NotRequired[Nullable[List[ValidDataTypeLinksTypedDict]]] - r"""The validDatatypeLinks can be used to determine whether an account can be correctly mapped to another object; for example, accounts with a `type` of `income` might only support being used on an Invoice and Direct Income. For more information, see [Valid Data Type Links](/sync-for-expenses-api#/schemas/ValidDataTypeLinks).""" - - -class AccountPrototype(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_. - - ## 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. - """ - - current_balance: Annotated[ - Annotated[ - OptionalNullable[Decimal], - BeforeValidator(validate_decimal), - PlainSerializer(serialize_decimal(False)), - ], - pydantic.Field(alias="currentBalance"), - ] = UNSET - r"""Current balance in the account.""" - - description: OptionalNullable[str] = UNSET - r"""Description for the account.""" - - fully_qualified_category: Annotated[ - OptionalNullable[str], pydantic.Field(alias="fullyQualifiedCategory") - ] = UNSET - r"""Full category of the account. - - For example, `Liability.Current` or `Income.Revenue`. To determine a list of possible categories for each integration, see our examples, follow our [Create, update, delete data](https://docs.codat.io/using-the-api/push) guide, or refer to the integration's own documentation. + _nullable = {'currentBalance', 'current_balance', 'description', 'fullyQualifiedCategory', 'fullyQualifiedName', 'fully_qualified_category', 'fully_qualified_name', 'name', 'nominalCode', 'nominal_code', 'validDatatypeLinks', 'valid_datatype_links'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } """ - - fully_qualified_name: Annotated[ - OptionalNullable[str], pydantic.Field(alias="fullyQualifiedName") - ] = UNSET - r"""Full name of the account, for example: - - `Cash On Hand` - - `Rents Held In Trust` - - `Fixed Asset` - """ - - is_bank_account: Annotated[ - Optional[bool], pydantic.Field(alias="isBankAccount") - ] = None - r"""Confirms whether the account is a bank account or not.""" - - name: OptionalNullable[str] = UNSET - r"""Name of the account.""" - - 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.""" - - status: Optional[AccountStatus] = None - r"""Status of the account""" - - supplemental_data: Annotated[ - Optional[SupplementalData], pydantic.Field(alias="supplementalData") - ] = None - r"""Supplemental data is additional data you can include in our standard data types. - - It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. - """ - + AccountPrototype + """ # noqa: E501 + 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.") + description: OptionalNullable[str] = Field(default=UNSET, description="Description for the account.") + fully_qualified_category: OptionalNullable[str] = Field(default=UNSET, description="Full category of the account. For example, `Liability.Current` or `Income.Revenue`. To determine a list of possible categories for each integration, see our examples, follow our [Create, update, delete data](https://docs.codat.io/using-the-api/push) guide, or refer to the integration's own documentation.", alias="fullyQualifiedCategory") + fully_qualified_name: OptionalNullable[str] = Field(default=UNSET, description="Full name of the account, for example: - `Cash On Hand` - `Rents Held In Trust` - `Fixed Asset`", alias="fullyQualifiedName") + 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.") + current_balance: Annotated[OptionalNullable[Decimal], BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(default=UNSET, description="Current balance in the account.", alias="currentBalance") type: Optional[AccountType] = None - r"""Type of account""" - - valid_datatype_links: Annotated[ - OptionalNullable[List[ValidDataTypeLinks]], - pydantic.Field(alias="validDatatypeLinks"), - ] = UNSET - r"""The validDatatypeLinks can be used to determine whether an account can be correctly mapped to another object; for example, accounts with a `type` of `income` might only support being used on an Invoice and Direct Income. For more information, see [Valid Data Type Links](/sync-for-expenses-api#/schemas/ValidDataTypeLinks).""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "currency", - "currentBalance", - "description", - "fullyQualifiedCategory", - "fullyQualifiedName", - "isBankAccount", - "name", - "nominalCode", - "status", - "supplementalData", - "type", - "validDatatypeLinks", - ] - ) - nullable_fields = set( - [ - "currentBalance", - "description", - "fullyQualifiedCategory", - "fullyQualifiedName", - "name", - "nominalCode", - "validDatatypeLinks", - ] + status: Optional[AccountStatus] = None + is_bank_account: Optional[bool] = Field(default=None, description="Confirms whether the account is a bank account or not.", alias="isBankAccount") + valid_datatype_links: OptionalNullable[List[ValidDataTypeLinks]] = Field(default=UNSET, description="The validDatatypeLinks can be used to determine whether an account can be correctly mapped to another object; for example, accounts with a `type` of `income` might only support being used on an Invoice and Direct Income. For more information, see [Valid Data Type Links](/sync-for-expenses-api#/schemas/ValidDataTypeLinks).", alias="validDatatypeLinks") + supplemental_data: Optional[SupplementalData] = Field(default=None, alias="supplementalData") + __properties: ClassVar[List[str]] = ["nominalCode", "name", "description", "fullyQualifiedCategory", "fullyQualifiedName", "currency", "currentBalance", "type", "status", "isBankAccount", "validDatatypeLinks", "supplementalData"] + + 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 AccountPrototype 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, ) - serialized = handler(self) - m = {} + # override the default output from pydantic by calling `to_dict()` of each item in valid_datatype_links (list) + _items = [] + if self.valid_datatype_links: + for _item_valid_datatype_links in self.valid_datatype_links: + if _item_valid_datatype_links: + _items.append(_item_valid_datatype_links.to_dict()) + _dict['validDatatypeLinks'] = _items + # override the default output from pydantic by calling `to_dict()` of supplemental_data + if self.supplemental_data: + _dict['supplementalData'] = self.supplemental_data.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of AccountPrototype from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "nominalCode": obj.get("nominalCode"), + "name": obj.get("name"), + "description": obj.get("description"), + "fullyQualifiedCategory": obj.get("fullyQualifiedCategory"), + "fullyQualifiedName": obj.get("fullyQualifiedName"), + "currency": obj.get("currency"), + "currentBalance": obj.get("currentBalance"), + "type": obj.get("type"), + "status": obj.get("status"), + "isBankAccount": obj.get("isBankAccount"), + "validDatatypeLinks": [ValidDataTypeLinks.from_dict(_item) for _item in obj["validDatatypeLinks"]] if obj.get("validDatatypeLinks") is not None else None, + "supplementalData": SupplementalData.from_dict(obj["supplementalData"]) if obj.get("supplementalData") is not None else None + }) + return _obj - 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: - AccountPrototype.model_rebuild() -except NameError: - pass +class AccountPrototypeTypedDict(TypedDict): + """TypedDict variant of AccountPrototype, for dict-literal request/response inputs.""" + nominal_code: NotRequired[Optional[str]] + name: NotRequired[Optional[str]] + description: NotRequired[Optional[str]] + fully_qualified_category: NotRequired[Optional[str]] + fully_qualified_name: NotRequired[Optional[str]] + currency: NotRequired[Optional[str]] + current_balance: NotRequired[Optional[Decimal]] + type: NotRequired[Optional[AccountType]] + status: NotRequired[Optional[AccountStatus]] + is_bank_account: NotRequired[Optional[bool]] + valid_datatype_links: NotRequired[Optional[List[ValidDataTypeLinksTypedDict]]] + supplemental_data: NotRequired[Optional[SupplementalDataTypedDict]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/accountstatus.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/accountstatus.py index 2ae331abc..3745f50a6 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/accountstatus.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/accountstatus.py @@ -1,13 +1,40 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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"""Status of the account""" + """ + Status of the account + """ + + """ + allowed enum values + """ + UNKNOWN = 'Unknown' + ACTIVE = 'Active' + ARCHIVED = 'Archived' + PENDING = 'Pending' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of AccountStatus from a JSON string""" + return cls(json.loads(json_str)) + - UNKNOWN = "Unknown" - ACTIVE = "Active" - ARCHIVED = "Archived" - PENDING = "Pending" diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/accounttype.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/accounttype.py index b893d55ba..083226033 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/accounttype.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/accounttype.py @@ -1,15 +1,42 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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 AccountType(str, Enum): - r"""Type of account""" - - UNKNOWN = "Unknown" - ASSET = "Asset" - EXPENSE = "Expense" - INCOME = "Income" - LIABILITY = "Liability" - EQUITY = "Equity" + """ + Type of account + """ + + """ + allowed enum values + """ + UNKNOWN = 'Unknown' + ASSET = 'Asset' + EXPENSE = 'Expense' + INCOME = 'Income' + LIABILITY = 'Liability' + EQUITY = 'Equity' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of AccountType from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/adjustmenttransactionline.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/adjustmenttransactionline.py index 5ea4dd586..df6ca1ad2 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/adjustmenttransactionline.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/adjustmenttransactionline.py @@ -1,92 +1,135 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations -from .invoiceto import InvoiceTo, InvoiceToTypedDict -from .recordref import RecordRef, RecordRefTypedDict -from .trackingrefadjustmenttransaction import ( - TrackingRefAdjustmentTransaction, - TrackingRefAdjustmentTransactionTypedDict, -) -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from codat_sync_for_expenses.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 codat_sync_for_expenses.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 Any, ClassVar, Dict, List, Optional, Union from typing_extensions import Annotated, NotRequired, TypedDict +from codat_sync_for_expenses.models.shared.invoiceto import InvoiceTo, InvoiceToTypedDict +from codat_sync_for_expenses.models.shared.recordref import RecordRef, RecordRefTypedDict +from codat_sync_for_expenses.models.shared.trackingrefadjustmenttransaction import TrackingRefAdjustmentTransaction, TrackingRefAdjustmentTransactionTypedDict +from typing import Optional, Set +from typing_extensions import Self +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL +class AdjustmentTransactionLine(BaseModel): -class AdjustmentTransactionLineTypedDict(TypedDict): - account_ref: RecordRefTypedDict - amount: Decimal - r"""Amount of the line. A positive line represents a debit; a negative line represents a credit.""" - description: NotRequired[str] - r"""Any private, company notes about the transaction.""" - invoice_to: NotRequired[Nullable[InvoiceToTypedDict]] - r"""Unique identifier for the customer billed for the transaction. The `invoiceTo` object is currently supported only for QuickBooks Online and QuickBooks Desktop.""" - tracking_refs: NotRequired[ - Nullable[List[TrackingRefAdjustmentTransactionTypedDict]] - ] + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'invoiceTo', 'invoice_to', '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) + } + """ + AdjustmentTransactionLine + """ # noqa: E501 + amount: Annotated[Decimal, BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(description="Amount of the line. A positive line represents a debit; a negative line represents a credit.") + account_ref: RecordRef = Field(alias="accountRef") + description: Optional[str] = Field(default=None, description="Any private, company notes about the transaction.") + tracking_refs: OptionalNullable[List[TrackingRefAdjustmentTransaction]] = Field(default=UNSET, alias="trackingRefs") + invoice_to: OptionalNullable[InvoiceTo] = Field(default=UNSET, alias="invoiceTo") + __properties: ClassVar[List[str]] = ["amount", "accountRef", "description", "trackingRefs", "invoiceTo"] + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) -class AdjustmentTransactionLine(BaseModel): - account_ref: Annotated[RecordRef, pydantic.Field(alias="accountRef")] - amount: Annotated[ - Decimal, - BeforeValidator(validate_decimal), - PlainSerializer(serialize_decimal(False)), - ] - r"""Amount of the line. A positive line represents a debit; a negative line represents a credit.""" + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - description: Optional[str] = None - r"""Any private, company notes about the transaction.""" + 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()) - invoice_to: Annotated[ - OptionalNullable[InvoiceTo], pydantic.Field(alias="invoiceTo") - ] = UNSET - r"""Unique identifier for the customer billed for the transaction. The `invoiceTo` object is currently supported only for QuickBooks Online and QuickBooks Desktop.""" + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of AdjustmentTransactionLine from a JSON string""" + return cls.from_dict(json.loads(json_str)) - tracking_refs: Annotated[ - OptionalNullable[List[TrackingRefAdjustmentTransaction]], - pydantic.Field(alias="trackingRefs"), - ] = UNSET + 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(["description", "invoiceTo", "trackingRefs"]) - nullable_fields = set(["invoiceTo", "trackingRefs"]) - 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: - AdjustmentTransactionLine.model_rebuild() -except NameError: - pass + 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 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 + # override the default output from pydantic by calling `to_dict()` of invoice_to + if self.invoice_to: + _dict['invoiceTo'] = self.invoice_to.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of AdjustmentTransactionLine 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"), + "accountRef": RecordRef.from_dict(obj["accountRef"]) if obj.get("accountRef") is not None else None, + "description": obj.get("description"), + "trackingRefs": [TrackingRefAdjustmentTransaction.from_dict(_item) for _item in obj["trackingRefs"]] if obj.get("trackingRefs") is not None else None, + "invoiceTo": InvoiceTo.from_dict(obj["invoiceTo"]) if obj.get("invoiceTo") is not None else None + }) + return _obj + + + + + +class AdjustmentTransactionLineTypedDict(TypedDict): + """TypedDict variant of AdjustmentTransactionLine, for dict-literal request/response inputs.""" + amount: NotRequired[Decimal] + account_ref: NotRequired[RecordRefTypedDict] + description: NotRequired[Optional[str]] + tracking_refs: NotRequired[Optional[List[TrackingRefAdjustmentTransactionTypedDict]]] + invoice_to: NotRequired[Optional[InvoiceToTypedDict]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/adjustmenttransactionrequest.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/adjustmenttransactionrequest.py index 600303914..8c0490f0d 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/adjustmenttransactionrequest.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/adjustmenttransactionrequest.py @@ -1,197 +1,130 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .adjustmenttransactionline import ( - AdjustmentTransactionLine, - AdjustmentTransactionLineTypedDict, -) -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from codat_sync_for_expenses.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 AdjustmentTransactionRequestTypedDict(TypedDict): - currency: str - r"""Currency the transaction was recorded in.""" - date_: 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: +""" + Expenses - ``` - 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. - """ - id: str - r"""Your unique identifier for the transaction.""" - lines: List[AdjustmentTransactionLineTypedDict] - r"""Array of transaction lines.""" - 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. + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | - Currency rates in Codat are implemented as the multiple of foreign currency units to each base currency unit. + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - 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. + Do not edit the class manually. +""" # noqa: E501 - 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. | - """ - reference: NotRequired[Nullable[str]] - r"""User-friendly reference for the adjustment transaction.""" +from __future__ import annotations +from decimal import Decimal +from codat_sync_for_expenses.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 Any, ClassVar, Dict, List, Optional, Union +from typing_extensions import Annotated, NotRequired, TypedDict +from codat_sync_for_expenses.models.shared.adjustmenttransactionline import AdjustmentTransactionLine, AdjustmentTransactionLineTypedDict +from typing import Optional, Set +from typing_extensions import Self +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL class AdjustmentTransactionRequest(BaseModel): - currency: str - r"""Currency the transaction was recorded in.""" - date_: Annotated[str, pydantic.Field(alias="date")] - 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 = {'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) + } """ + AdjustmentTransactionRequest + """ # noqa: E501 + id: str = Field(description="Your unique identifier for the transaction.") + date_: str = Field(description="Date of the transaction.", alias="date") + currency: str = Field(description="Currency the transaction was recorded in.") + 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") + reference: OptionalNullable[str] = Field(default=UNSET, description="User-friendly reference for the adjustment transaction.") + lines: List[AdjustmentTransactionLine] = Field(description="Array of transaction lines.") + __properties: ClassVar[List[str]] = ["id", "date", "currency", "currencyRate", "reference", "lines"] + + 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 AdjustmentTransactionRequest 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 lines (list) + _items = [] + if self.lines: + for _item_lines in self.lines: + if _item_lines: + _items.append(_item_lines.to_dict()) + _dict['lines'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of AdjustmentTransactionRequest 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"), + "date": obj.get("date"), + "currency": obj.get("currency"), + "currencyRate": obj.get("currencyRate"), + "reference": obj.get("reference"), + "lines": [AdjustmentTransactionLine.from_dict(_item) for _item in obj["lines"]] if obj.get("lines") is not None else None + }) + return _obj - id: str - r"""Your unique identifier for the transaction.""" - - lines: List[AdjustmentTransactionLine] - r"""Array of transaction lines.""" - - 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 | - - - ### 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. | - """ - - reference: OptionalNullable[str] = UNSET - r"""User-friendly reference for the adjustment transaction.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["currencyRate", "reference"]) - nullable_fields = set(["currencyRate", "reference"]) - 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: - AdjustmentTransactionRequest.model_rebuild() -except NameError: - pass +class AdjustmentTransactionRequestTypedDict(TypedDict): + """TypedDict variant of AdjustmentTransactionRequest, for dict-literal request/response inputs.""" + id: NotRequired[str] + date_: NotRequired[str] + currency: NotRequired[str] + currency_rate: NotRequired[Optional[Decimal]] + reference: NotRequired[Optional[str]] + lines: NotRequired[List[AdjustmentTransactionLineTypedDict]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/adjustmenttransactionresponse.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/adjustmenttransactionresponse.py index 6dbd571af..6999c917b 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/adjustmenttransactionresponse.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/adjustmenttransactionresponse.py @@ -1,40 +1,99 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class AdjustmentTransactionResponseTypedDict(TypedDict): - sync_id: NotRequired[str] - r"""Unique id of sync created""" + The version of the OpenAPI document: prealpha + Contact: expenses@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 AdjustmentTransactionResponse(BaseModel): - sync_id: Annotated[Optional[str], pydantic.Field(alias="syncId")] = None - r"""Unique id of sync created""" @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["syncId"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + AdjustmentTransactionResponse + """ # noqa: E501 + sync_id: Optional[str] = Field(default=None, description="Unique id of sync created", alias="syncId") + __properties: ClassVar[List[str]] = ["syncId"] + + 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 AdjustmentTransactionResponse 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: - AdjustmentTransactionResponse.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 AdjustmentTransactionResponse from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "syncId": obj.get("syncId") + }) + return _obj + + + + + +class AdjustmentTransactionResponseTypedDict(TypedDict): + """TypedDict variant of AdjustmentTransactionResponse, for dict-literal request/response inputs.""" + sync_id: NotRequired[Optional[str]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/apaccountref.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/apaccountref.py index 2ec0a5f5d..646f25517 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/apaccountref.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/apaccountref.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_expenses.types import BaseModel, UNSET_SENTINEL -from pydantic import model_serializer -from typing import Optional -from typing_extensions import NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class ApAccountRefTypedDict(TypedDict): - id: NotRequired[str] - r"""Unique identifier for the Accounts Payable account associated with the transaction. The `apAccountRef` object is currently supported only for QuickBooks Desktop.""" + The version of the OpenAPI document: prealpha + Contact: expenses@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 ApAccountRef(BaseModel): - id: Optional[str] = None - r"""Unique identifier for the Accounts Payable account associated with the transaction. The `apAccountRef` object is currently supported only for QuickBooks Desktop.""" @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} + """ + ApAccountRef + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Unique identifier for the Accounts Payable account associated with the transaction. The `apAccountRef` object is currently supported only for QuickBooks Desktop.") + __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 ApAccountRef 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 ApAccountRef 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 ApAccountRefTypedDict(TypedDict): + """TypedDict variant of ApAccountRef, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/attachment.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/attachment.py index 18ece7699..179e33edd 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/attachment.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/attachment.py @@ -1,52 +1,105 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class AttachmentTypedDict(TypedDict): - company_id: NotRequired[str] - r"""Unique ID of company in Codat""" - id: NotRequired[str] - r"""Unique identifier of attachment""" - transaction_id: NotRequired[str] - r"""Unique identifier of transaction""" + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class Attachment(BaseModel): - company_id: Annotated[Optional[str], pydantic.Field(alias="companyId")] = None - r"""Unique ID of company in Codat""" - id: Optional[str] = None - r"""Unique identifier of attachment""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - transaction_id: Annotated[Optional[str], pydantic.Field(alias="transactionId")] = ( - None - ) - r"""Unique identifier of transaction""" +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 Attachment(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["companyId", "id", "transactionId"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + Attachment + """ # noqa: E501 + company_id: Optional[str] = Field(default=None, description="Unique ID of company in Codat", alias="companyId") + id: Optional[str] = Field(default=None, description="Unique identifier of attachment") + transaction_id: Optional[str] = Field(default=None, description="Unique identifier of transaction", alias="transactionId") + __properties: ClassVar[List[str]] = ["companyId", "id", "transactionId"] + + 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 Attachment 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: - Attachment.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, + ) + return _dict + + @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 + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "companyId": obj.get("companyId"), + "id": obj.get("id"), + "transactionId": obj.get("transactionId") + }) + return _obj + + + + + +class AttachmentTypedDict(TypedDict): + """TypedDict variant of Attachment, for dict-literal request/response inputs.""" + company_id: NotRequired[Optional[str]] + id: NotRequired[Optional[str]] + transaction_id: NotRequired[Optional[str]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/attachmentupload.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/attachmentupload.py index 1cf8149b8..740960ca4 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/attachmentupload.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/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_expenses.types import BaseModel -from codat_sync_for_expenses.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_expenses.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-expenses/src/codat_sync_for_expenses/models/shared/bankaccount.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/bankaccount.py index a34a0db90..3e5d6a290 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/bankaccount.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/bankaccount.py @@ -1,298 +1,175 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .bankaccountstatus import BankAccountStatus -from .metadata import Metadata, MetadataTypedDict -from .supplementaldata import SupplementalData, SupplementalDataTypedDict -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from codat_sync_for_expenses.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 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. - """ - - UNKNOWN = "Unknown" - CREDIT = "Credit" - DEBIT = "Debit" - - -class BankAccountTypedDict(TypedDict): - r"""> **Accessing Bank Accounts through Banking API** - > - > This datatype was originally used for accessing bank account data both in accounting integrations and open banking aggregators. - > - > To view bank account data through the Banking API, please refer to the new [Banking: Account](https://docs.codat.io/sync-for-expenses-api#/schemas/Account) data type. - - ## Overview - - A list of bank accounts associated with a company and a specific data connection. - - Bank accounts data includes: - * The name and ID of the account in the accounting software. - * The currency and balance of the account. - * The sort code and account number. - """ - - account_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. - - FreeAgent integrations - For Credit accounts, only the last four digits are required. For other types, the field is optional. - """ - 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. - """ - available_balance: NotRequired[Nullable[Decimal]] - r"""Total available balance of the bank account as reported by the underlying data source. This may take into account overdrafts or pending transactions for example.""" - balance: NotRequired[Nullable[Decimal]] - r"""Balance of the bank 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. +""" + Expenses - There are only a very small number of edge cases where this currency code is returned by the Codat system. - """ - i_ban: NotRequired[Nullable[str]] - r"""International bank account number of the account. Often used when making or receiving international payments.""" - id: NotRequired[str] - r"""Identifier for the account, unique for the company in the accounting software.""" - institution: NotRequired[Nullable[str]] - r"""The institution of the bank account.""" - metadata: NotRequired[MetadataTypedDict] - modified_date: NotRequired[str] - nominal_code: NotRequired[Nullable[str]] - r"""Code used to identify each nominal account for a business.""" - overdraft_limit: NotRequired[Nullable[Decimal]] - r"""Pre-arranged overdraft limit of the account. - - The value is always positive. For example, an overdraftLimit of `1000` means that the balance of the account can go down to `-1000`. - """ - sort_code: NotRequired[Nullable[str]] - r"""Sort code for the bank account. + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | - 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: NotRequired[str] - status: NotRequired[BankAccountStatus] - r"""Status of the bank account.""" - supplemental_data: NotRequired[SupplementalDataTypedDict] - r"""Supplemental data is additional data you can include in our standard data types. + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. - """ + Do not edit the class manually. +""" # noqa: E501 +from __future__ import annotations +from decimal import Decimal +from codat_sync_for_expenses.utils.serializers import serialize_decimal, validate_decimal +from codat_sync_for_expenses.models.shared.accounttype import AccountType +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 codat_sync_for_expenses.models.shared.bankaccountstatus import BankAccountStatus +from codat_sync_for_expenses.models.shared.metadata import Metadata, MetadataTypedDict +from codat_sync_for_expenses.models.shared.supplementaldata import SupplementalData, SupplementalDataTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_sync_for_expenses.models.bank_account_type import BankAccountType +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL class BankAccount(BaseModel): - r"""> **Accessing Bank Accounts through Banking API** - > - > This datatype was originally used for accessing bank account data both in accounting integrations and open banking aggregators. - > - > To view bank account data through the Banking API, please refer to the new [Banking: Account](https://docs.codat.io/sync-for-expenses-api#/schemas/Account) data type. - - ## Overview - - A list of bank accounts associated with a company and a specific data connection. - - Bank accounts data includes: - * The name and ID of the account in the accounting software. - * The currency and balance of the account. - * The sort code and account number. - """ - - account_name: Annotated[ - OptionalNullable[str], pydantic.Field(alias="accountName") - ] = UNSET - r"""Name of the bank account in the accounting software.""" - account_number: Annotated[ - OptionalNullable[str], pydantic.Field(alias="accountNumber") - ] = UNSET - 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. - - FreeAgent integrations - For Credit accounts, only the last four digits are required. For other types, the field is optional. - """ - - 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. - """ - - available_balance: Annotated[ - Annotated[ - OptionalNullable[Decimal], - BeforeValidator(validate_decimal), - PlainSerializer(serialize_decimal(False)), - ], - pydantic.Field(alias="availableBalance"), - ] = UNSET - r"""Total available balance of the bank account as reported by the underlying data source. This may take into account overdrafts or pending transactions for example.""" - - balance: Annotated[ - OptionalNullable[Decimal], - BeforeValidator(validate_decimal), - PlainSerializer(serialize_decimal(False)), - ] = UNSET - r"""Balance of the bank account.""" - - 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_. - - ## 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 = {'accountName', 'accountNumber', 'account_name', 'account_number', 'availableBalance', 'available_balance', 'balance', 'iBan', 'i_ban', 'institution', 'nominalCode', 'nominal_code', 'overdraftLimit', 'overdraft_limit', '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) + } """ - - i_ban: Annotated[OptionalNullable[str], pydantic.Field(alias="iBan")] = UNSET - r"""International bank account number of the account. Often used when making or receiving international payments.""" - - id: Optional[str] = None - r"""Identifier for the account, unique for the company in the accounting software.""" - - institution: OptionalNullable[str] = UNSET - r"""The institution of the bank account.""" - + > **Accessing Bank Accounts through Banking API** > > This datatype was originally used for accessing bank account data both in accounting integrations and open banking aggregators. > > To view bank account data through the Banking API, please refer to the new [Banking: Account](https://docs.codat.io/sync-for-expenses-api#/schemas/Account) data type. ## Overview A list of bank accounts associated with a company and a specific data connection. Bank accounts data includes: * The name and ID of the account in the accounting software. * The currency and balance of the account. * The sort code and account number. + """ # noqa: E501 + account_name: OptionalNullable[str] = Field(default=UNSET, description="Name of the bank account in the accounting software.", alias="accountName") + account_type: Optional[BankAccountType] = Field(default=None, description="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.", alias="accountType") + 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") + 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. FreeAgent integrations For Credit accounts, only the last four digits are required. For other types, the field is optional.", alias="accountNumber") + i_ban: OptionalNullable[str] = Field(default=UNSET, description="International bank account number of the account. Often used when making or receiving international payments.", alias="iBan") + 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.") + balance: Annotated[OptionalNullable[Decimal], BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(default=UNSET, description="Balance of the bank account.") + institution: OptionalNullable[str] = Field(default=UNSET, description="The institution of the bank account.") + available_balance: Annotated[OptionalNullable[Decimal], BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(default=UNSET, description="Total available balance of the bank account as reported by the underlying data source. This may take into account overdrafts or pending transactions for example.", alias="availableBalance") + overdraft_limit: Annotated[OptionalNullable[Decimal], BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(default=UNSET, description="Pre-arranged overdraft limit of the account. The value is always positive. For example, an overdraftLimit of `1000` means that the balance of the account can go down to `-1000`.", alias="overdraftLimit") + status: Optional[BankAccountStatus] = None + modified_date: Optional[str] = Field(default=None, description="The date when the record was last fetched from the accounting software, commerce software, or open banking provider and updated in Codat’s data cache. Use it to identify and retrieve records that have changed since your last fetch. For example, filtering `modifiedDate` to today will provide new records updated in Codat today. This date is populated for all data types except for attachments, balance sheets, company information, and profit & loss reports ([read more](https://docs.codat.io/using-the-api/modified-dates#modified-date)). In Codat's data model, dates and times are represented using the ISO 8601 standard.", alias="modifiedDate") + 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.") metadata: Optional[Metadata] = None + supplemental_data: Optional[SupplementalData] = Field(default=None, alias="supplementalData") + __properties: ClassVar[List[str]] = ["accountName", "accountType", "nominalCode", "sortCode", "accountNumber", "iBan", "currency", "balance", "institution", "availableBalance", "overdraftLimit", "status", "modifiedDate", "sourceModifiedDate", "id", "metadata", "supplementalData"] + + @field_validator('account_type') + def account_type_validate_enum(cls, value): + """Validates the enum""" + if value is None: + return value + + if value not in set(['Unknown', 'Credit', 'Debit']): + raise ValueError("must be one of enum values ('Unknown', 'Credit', 'Debit')") + return value + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) - modified_date: Annotated[Optional[str], pydantic.Field(alias="modifiedDate")] = None - - nominal_code: Annotated[ - OptionalNullable[str], pydantic.Field(alias="nominalCode") - ] = UNSET - r"""Code used to identify each nominal account for a business.""" - overdraft_limit: Annotated[ - Annotated[ - OptionalNullable[Decimal], - BeforeValidator(validate_decimal), - PlainSerializer(serialize_decimal(False)), - ], - pydantic.Field(alias="overdraftLimit"), - ] = UNSET - r"""Pre-arranged overdraft limit of the account. + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - The value is always positive. For example, an overdraftLimit of `1000` means that the balance of the account can go down to `-1000`. - """ + 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()) - sort_code: Annotated[OptionalNullable[str], pydantic.Field(alias="sortCode")] = ( - UNSET - ) - r"""Sort code for the bank account. + @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)) - 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. - """ + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - source_modified_date: Annotated[ - Optional[str], pydantic.Field(alias="sourceModifiedDate") - ] = None + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - status: Optional[BankAccountStatus] = None - r"""Status of the bank account.""" + * `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([ + ]) - supplemental_data: Annotated[ - Optional[SupplementalData], pydantic.Field(alias="supplementalData") - ] = None - r"""Supplemental data is additional data you can include in our standard data types. - - It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. - """ - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "accountName", - "accountNumber", - "accountType", - "availableBalance", - "balance", - "currency", - "iBan", - "id", - "institution", - "metadata", - "modifiedDate", - "nominalCode", - "overdraftLimit", - "sortCode", - "sourceModifiedDate", - "status", - "supplementalData", - ] + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, ) - nullable_fields = set( - [ - "accountName", - "accountNumber", - "availableBalance", - "balance", - "iBan", - "institution", - "nominalCode", - "overdraftLimit", - "sortCode", - ] - ) - serialized = handler(self) - m = {} + # override the default output from pydantic by calling `to_dict()` of metadata + if self.metadata: + _dict['metadata'] = self.metadata.to_dict() + # override the default output from pydantic by calling `to_dict()` of supplemental_data + if self.supplemental_data: + _dict['supplementalData'] = self.supplemental_data.to_dict() + return _dict + + @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 + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "accountName": obj.get("accountName"), + "accountType": obj.get("accountType"), + "nominalCode": obj.get("nominalCode"), + "sortCode": obj.get("sortCode"), + "accountNumber": obj.get("accountNumber"), + "iBan": obj.get("iBan"), + "currency": obj.get("currency"), + "balance": obj.get("balance"), + "institution": obj.get("institution"), + "availableBalance": obj.get("availableBalance"), + "overdraftLimit": obj.get("overdraftLimit"), + "status": obj.get("status"), + "modifiedDate": obj.get("modifiedDate"), + "sourceModifiedDate": obj.get("sourceModifiedDate"), + "id": obj.get("id"), + "metadata": Metadata.from_dict(obj["metadata"]) if obj.get("metadata") is not None else None, + "supplementalData": SupplementalData.from_dict(obj["supplementalData"]) if obj.get("supplementalData") is not None else None + }) + return _obj - 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.""" + account_name: NotRequired[Optional[str]] + account_type: NotRequired[Optional[BankAccountType]] + nominal_code: NotRequired[Optional[str]] + sort_code: NotRequired[Optional[str]] + account_number: NotRequired[Optional[str]] + i_ban: NotRequired[Optional[str]] + currency: NotRequired[Optional[str]] + balance: NotRequired[Optional[Decimal]] + institution: NotRequired[Optional[str]] + available_balance: NotRequired[Optional[Decimal]] + overdraft_limit: NotRequired[Optional[Decimal]] + status: NotRequired[Optional[BankAccountStatus]] + modified_date: NotRequired[Optional[str]] + source_modified_date: NotRequired[Optional[str]] + id: NotRequired[Optional[str]] + metadata: NotRequired[Optional[MetadataTypedDict]] + supplemental_data: NotRequired[Optional[SupplementalDataTypedDict]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/bankaccountdetails.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/bankaccountdetails.py index 184b56e0e..01556abd9 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/bankaccountdetails.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/bankaccountdetails.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_expenses.types import BaseModel, UNSET_SENTINEL -from pydantic import model_serializer -from typing import Optional -from typing_extensions import NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class BankAccountDetailsTypedDict(TypedDict): - id: NotRequired[str] - r"""The id of the account from which purchases are made""" + The version of the OpenAPI document: prealpha + Contact: expenses@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 BankAccountDetails(BaseModel): - id: Optional[str] = None - r"""The id of the account from which purchases are made""" @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} + """ + BankAccountDetails + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="The id of the account from which purchases are made") + __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 BankAccountDetails 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 BankAccountDetails 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 BankAccountDetailsTypedDict(TypedDict): + """TypedDict variant of BankAccountDetails, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/bankaccountstatus.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/bankaccountstatus.py index be857f929..87bfe1173 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/bankaccountstatus.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/bankaccountstatus.py @@ -1,13 +1,40 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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"""Status of the bank account.""" + """ + Status of the bank account. + """ + + """ + allowed enum values + """ + UNKNOWN = 'Unknown' + ACTIVE = 'Active' + ARCHIVED = 'Archived' + PENDING = 'Pending' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of BankAccountStatus from a JSON string""" + return cls(json.loads(json_str)) + - UNKNOWN = "Unknown" - ACTIVE = "Active" - ARCHIVED = "Archived" - PENDING = "Pending" diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/clientratelimitwebhook.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/clientratelimitwebhook.py index 11951050a..617a16759 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/clientratelimitwebhook.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/clientratelimitwebhook.py @@ -1,97 +1,112 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .clientratelimitwebhookpayload import ( - ClientRateLimitWebhookPayload, - ClientRateLimitWebhookPayloadTypedDict, -) -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class ClientRateLimitWebhookTypedDict(TypedDict): - event_type: NotRequired[str] - r"""The type of event.""" - generated_date: 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: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + Do not edit the class manually. +""" # noqa: E501 +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_sync_for_expenses.models.shared.clientratelimitwebhookpayload import ClientRateLimitWebhookPayload, ClientRateLimitWebhookPayloadTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict - - 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` +class ClientRateLimitWebhook(BaseModel): - > 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) + return {k: v for k, v in serialized.items() if v is not None} """ - id: NotRequired[str] - r"""Unique identifier of the event.""" - payload: NotRequired[ClientRateLimitWebhookPayloadTypedDict] + 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="The date time in UTC the event was generated in Codat.", 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=(), + ) -class ClientRateLimitWebhook(BaseModel): - event_type: Annotated[Optional[str], pydantic.Field(alias="eventType")] = None - r"""The type of event.""" - generated_date: Annotated[Optional[str], pydantic.Field(alias="generatedDate")] = ( - 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_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + 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. - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - - 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` + * `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([ + ]) - > 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. - """ + _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 - id: Optional[str] = None - r"""Unique identifier of the event.""" + @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 - payload: Optional[ClientRateLimitWebhookPayload] = None + if not isinstance(obj, dict): + return cls.model_validate(obj) - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["eventType", "generatedDate", "id", "payload"]) - serialized = handler(self) - m = {} + _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 - 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: - ClientRateLimitWebhook.model_rebuild() -except NameError: - pass +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-expenses/src/codat_sync_for_expenses/models/shared/clientratelimitwebhookpayload.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/clientratelimitwebhookpayload.py index 32347701a..2991ecd8b 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/clientratelimitwebhookpayload.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/clientratelimitwebhookpayload.py @@ -1,90 +1,105 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class ClientRateLimitWebhookPayloadTypedDict(TypedDict): - daily_quota: NotRequired[int] - r"""The number of available requests per day.""" - expiry_date: 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: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + Do not edit the class manually. +""" # noqa: E501 +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: +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 - - 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` +class ClientRateLimitWebhookPayload(BaseModel): - > 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) + return {k: v for k, v in serialized.items() if v is not None} """ - quota_remaining: NotRequired[int] - r"""Total number of requests remaining for your client.""" + 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="The date time in UTC when your daily quota is reset.", alias="expiryDate") + __properties: ClassVar[List[str]] = ["dailyQuota", "quotaRemaining", "expiryDate"] + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) -class ClientRateLimitWebhookPayload(BaseModel): - daily_quota: Annotated[Optional[int], pydantic.Field(alias="dailyQuota")] = None - r"""The number of available requests per day.""" - expiry_date: Annotated[Optional[str], pydantic.Field(alias="expiryDate")] = 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_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + 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. - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - - 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` + * `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([ + ]) - > 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. - """ + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict - quota_remaining: Annotated[ - Optional[int], pydantic.Field(alias="quotaRemaining") - ] = None - r"""Total number of requests remaining for your client.""" + @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 - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["dailyQuota", "expiryDate", "quotaRemaining"]) - serialized = handler(self) - m = {} + 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 - 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: - ClientRateLimitWebhookPayload.model_rebuild() -except NameError: - pass +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-expenses/src/codat_sync_for_expenses/models/shared/codatfile.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/codatfile.py index 136e0524c..0adbb4fae 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/codatfile.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/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_expenses.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_expenses.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): - content: Union[bytes, IO[bytes], io.BufferedReader] - file_name: str - 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): - content: Annotated[ - Union[bytes, IO[bytes], io.BufferedReader], - pydantic.Field(alias=""), - FieldMetadata(multipart=MultipartFormMetadata(content=True)), - ] - - file_name: Annotated[ - str, pydantic.Field(alias="fileName"), FieldMetadata(multipart=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-expenses/src/codat_sync_for_expenses/models/shared/companies.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/companies.py index 499df6ab6..2920a58e0 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/companies.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/companies.py @@ -1,58 +1,124 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.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_expenses.models.shared.company import Company, CompanyTypedDict +from codat_sync_for_expenses.models.shared.links import Links, LinksTypedDict +from typing import Optional, Set +from typing_extensions import Self +class Companies(BaseModel): -class CompaniesTypedDict(TypedDict): - links: LinksTypedDict - 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.""" - 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): - links: Annotated[Links, pydantic.Field(alias="_links")] - page_number: Annotated[int, pydantic.Field(alias="pageNumber")] - r"""Current page number.""" + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - page_size: Annotated[int, pydantic.Field(alias="pageSize")] - r"""Number of items to return in results array.""" + 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()) - total_results: Annotated[int, pydantic.Field(alias="totalResults")] - r"""Total number of items.""" + @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-expenses/src/codat_sync_for_expenses/models/shared/company.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/company.py index 04af6f014..d188466fb 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/company.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/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_expenses.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 +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -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-expenses-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.""" - 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: + The version of the OpenAPI document: prealpha + Contact: expenses@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_by_user_name: NotRequired[Nullable[str]] - r"""Name of user that created the company in Codat.""" - data_connections: NotRequired[List[ConnectionTypedDict]] - 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: + 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_expenses.models.shared.companyreference import CompanyReference, CompanyReferenceTypedDict +from codat_sync_for_expenses.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. - """ - products: NotRequired[List[str]] - r"""An array of products that are currently enabled for 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.""" - tags: NotRequired[Dict[str, str]] - r"""A collection of user-defined key-value pairs that store custom metadata against the company.""" - - +from codat_sync_for_expenses.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-expenses-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.""" - - 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. - """ - - created_by_user_name: Annotated[ - OptionalNullable[str], pydantic.Field(alias="createdByUserName") - ] = UNSET - r"""Name of user that created the company in Codat.""" - - data_connections: Annotated[ - Optional[List[Connection]], pydantic.Field(alias="dataConnections") - ] = None - - 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. + @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-expenses-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="A description of the property.") + 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="Date of the transfer transaction as recorded in the accounting software.", alias="lastSync") + created: Optional[str] = Field(default=None, description="Date of the transfer transaction as recorded in the accounting software.") + 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 - products: Optional[List[str]] = None - r"""An array of products that are currently enabled for 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.""" - tags: Optional[Dict[str, str]] = None - r"""A collection of user-defined key-value pairs that store custom metadata against the company.""" - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "created", - "createdByUserName", - "dataConnections", - "description", - "lastSync", - "products", - "referenceParentCompany", - "referenceSubsidiaryCompanies", - "tags", - ] - ) - 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-expenses/src/codat_sync_for_expenses/models/shared/companyconfiguration.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/companyconfiguration.py index e990d8d9a..3d3b498a0 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/companyconfiguration.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/companyconfiguration.py @@ -1,29 +1,117 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .bankaccountdetails import BankAccountDetails, BankAccountDetailsTypedDict -from .customerdetails import CustomerDetails, CustomerDetailsTypedDict -from .supplierdetails import SupplierDetails, SupplierDetailsTypedDict -from codat_sync_for_expenses.types import BaseModel -import pydantic -from typing_extensions import Annotated, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class CompanyConfigurationTypedDict(TypedDict): - bank_account: BankAccountDetailsTypedDict - customer: CustomerDetailsTypedDict - supplier: SupplierDetailsTypedDict + The version of the OpenAPI document: prealpha + Contact: expenses@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 codat_sync_for_expenses.models.shared.bankaccountdetails import BankAccountDetails, BankAccountDetailsTypedDict +from codat_sync_for_expenses.models.shared.customerdetails import CustomerDetails, CustomerDetailsTypedDict +from codat_sync_for_expenses.models.shared.supplierdetails import SupplierDetails, SupplierDetailsTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict class CompanyConfiguration(BaseModel): - bank_account: Annotated[BankAccountDetails, pydantic.Field(alias="bankAccount")] + @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} + """ + CompanyConfiguration + """ # noqa: E501 + bank_account: BankAccountDetails = Field(alias="bankAccount") + supplier: SupplierDetails customer: CustomerDetails + __properties: ClassVar[List[str]] = ["bankAccount", "supplier", "customer"] - supplier: SupplierDetails + 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 CompanyConfiguration 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. -try: - CompanyConfiguration.model_rebuild() -except NameError: - pass + 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 bank_account + if self.bank_account: + _dict['bankAccount'] = self.bank_account.to_dict() + # override the default output from pydantic by calling `to_dict()` of supplier + if self.supplier: + _dict['supplier'] = self.supplier.to_dict() + # override the default output from pydantic by calling `to_dict()` of customer + if self.customer: + _dict['customer'] = self.customer.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CompanyConfiguration from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "bankAccount": BankAccountDetails.from_dict(obj["bankAccount"]) if obj.get("bankAccount") is not None else None, + "supplier": SupplierDetails.from_dict(obj["supplier"]) if obj.get("supplier") is not None else None, + "customer": CustomerDetails.from_dict(obj["customer"]) if obj.get("customer") is not None else None + }) + return _obj + + + + + +class CompanyConfigurationTypedDict(TypedDict): + """TypedDict variant of CompanyConfiguration, for dict-literal request/response inputs.""" + bank_account: NotRequired[BankAccountDetailsTypedDict] + supplier: SupplierDetailsTypedDict + customer: CustomerDetailsTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/companyinformation.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/companyinformation.py index 8f5ab8be4..03deea6cb 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/companyinformation.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/companyinformation.py @@ -1,485 +1,6 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - from __future__ import annotations -from .accountingaddresstype import AccountingAddressType -from .supplementaldata import SupplementalData, SupplementalDataTypedDict -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from enum import Enum -import pydantic -from pydantic import model_serializer -from typing import Dict, List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class AccountingAddressTypedDict(TypedDict): - type: AccountingAddressType - r"""The type of the address""" - city: NotRequired[Nullable[str]] - r"""City of the customer address.""" - country: NotRequired[Nullable[str]] - r"""Country of the customer address.""" - line1: NotRequired[Nullable[str]] - r"""Line 1 of the customer address.""" - line2: NotRequired[Nullable[str]] - r"""Line 2 of the customer address.""" - postal_code: NotRequired[Nullable[str]] - r"""Postal code or zip code.""" - region: NotRequired[Nullable[str]] - r"""Region of the customer address.""" - - -class AccountingAddress(BaseModel): - type: AccountingAddressType - r"""The type of the address""" - - city: OptionalNullable[str] = UNSET - r"""City of the customer address.""" - - country: OptionalNullable[str] = UNSET - r"""Country of the customer address.""" - - line1: OptionalNullable[str] = UNSET - r"""Line 1 of the customer address.""" - - line2: OptionalNullable[str] = UNSET - r"""Line 2 of the customer address.""" - - postal_code: Annotated[ - OptionalNullable[str], pydantic.Field(alias="postalCode") - ] = UNSET - r"""Postal code or zip code.""" - - region: OptionalNullable[str] = UNSET - r"""Region of the customer address.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - ["city", "country", "line1", "line2", "postalCode", "region"] - ) - nullable_fields = set( - ["city", "country", "line1", "line2", "postalCode", "region"] - ) - 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 - - -class CompanyInformationType(str, Enum): - r"""The type of phone number""" - - PRIMARY = "Primary" - LANDLINE = "Landline" - MOBILE = "Mobile" - FAX = "Fax" - UNKNOWN = "Unknown" - - -class PhoneTypedDict(TypedDict): - type: CompanyInformationType - r"""The type of phone number""" - number: NotRequired[Nullable[str]] - r"""A phone number.""" - - -class Phone(BaseModel): - type: CompanyInformationType - r"""The type of phone number""" - - number: OptionalNullable[str] = UNSET - r"""A phone number.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["number"]) - nullable_fields = set(["number"]) - 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 - - -class CompanyInformationSchemasType(str, Enum): - r"""The type of the weblink.""" - - WEBSITE = "Website" - SOCIAL = "Social" - UNKNOWN = "Unknown" - - -class WeblinkTypedDict(TypedDict): - r"""Weblink associated with the company.""" - - type: NotRequired[CompanyInformationSchemasType] - r"""The type of the weblink.""" - url: NotRequired[str] - r"""The full URL for the weblink.""" - - -class Weblink(BaseModel): - r"""Weblink associated with the company.""" - - type: Optional[CompanyInformationSchemasType] = None - r"""The type of the weblink.""" - - url: Optional[str] = None - r"""The full URL for the weblink.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["type", "url"]) - 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 CompanyInformationTypedDict(TypedDict): - r"""Company info provides standard details about a linked company such as their address, phone number, and company registration. - - > **Company information or companies?** - > - > Company information is standard information that is held in the accounting software about a company. `Companies` is an endpoint that lists businesses in the Codat system that have linked and shared their data sources. - """ - - accounting_platform_ref: NotRequired[Nullable[str]] - r"""Identifier or reference for the company in the accounting software.""" - addresses: NotRequired[Nullable[List[AccountingAddressTypedDict]]] - r"""An array of Addresses.""" - base_currency: NotRequired[Nullable[str]] - r"""Currency set in the accounting software of the linked company. Used by the currency rate.""" - company_legal_name: NotRequired[Nullable[str]] - r"""Registered legal name of the linked company.""" - company_name: NotRequired[Nullable[str]] - r"""Name of the linked company.""" - created_date: 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. - """ - financial_year_start_date: 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. - """ - ledger_lock_date: 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. - """ - phone_numbers: NotRequired[Nullable[List[PhoneTypedDict]]] - r"""An array of phone numbers.""" - registration_number: NotRequired[Nullable[str]] - r"""Registration number given to the linked company by the companies authority in the country of origin. In the UK this is Companies House.""" - source_urls: NotRequired[Nullable[Dict[str, Nullable[str]]]] - r"""URL addresses for the accounting source. - - For example, for Xero integrations two URLs are returned. These have many potential use cases, such as [deep linking](https://developer.xero.com/documentation/api-guides/deep-link-xero). - """ - supplemental_data: NotRequired[SupplementalDataTypedDict] - r"""Supplemental data is additional data you can include in our standard data types. - - It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. - """ - tax_number: NotRequired[Nullable[str]] - r"""Company tax number.""" - web_links: NotRequired[Nullable[List[WeblinkTypedDict]]] - r"""An array of weblinks.""" - - -class CompanyInformation(BaseModel): - r"""Company info provides standard details about a linked company such as their address, phone number, and company registration. - - > **Company information or companies?** - > - > Company information is standard information that is held in the accounting software about a company. `Companies` is an endpoint that lists businesses in the Codat system that have linked and shared their data sources. - """ - - accounting_platform_ref: Annotated[ - OptionalNullable[str], pydantic.Field(alias="accountingPlatformRef") - ] = UNSET - r"""Identifier or reference for the company in the accounting software.""" - - addresses: OptionalNullable[List[AccountingAddress]] = UNSET - r"""An array of Addresses.""" - - 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.""" - - company_legal_name: Annotated[ - OptionalNullable[str], pydantic.Field(alias="companyLegalName") - ] = UNSET - r"""Registered legal name of the linked company.""" - - company_name: Annotated[ - OptionalNullable[str], pydantic.Field(alias="companyName") - ] = UNSET - r"""Name of the linked company.""" - - created_date: Annotated[Optional[str], pydantic.Field(alias="createdDate")] = 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. - """ - - financial_year_start_date: Annotated[ - Optional[str], pydantic.Field(alias="financialYearStartDate") - ] = 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. - """ - - ledger_lock_date: Annotated[ - Optional[str], pydantic.Field(alias="ledgerLockDate") - ] = 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. - """ - - phone_numbers: Annotated[ - OptionalNullable[List[Phone]], pydantic.Field(alias="phoneNumbers") - ] = UNSET - r"""An array of phone numbers.""" - - registration_number: Annotated[ - OptionalNullable[str], pydantic.Field(alias="registrationNumber") - ] = UNSET - r"""Registration number given to the linked company by the companies authority in the country of origin. In the UK this is Companies House.""" - - source_urls: Annotated[ - OptionalNullable[Dict[str, Nullable[str]]], pydantic.Field(alias="sourceUrls") - ] = UNSET - r"""URL addresses for the accounting source. - - For example, for Xero integrations two URLs are returned. These have many potential use cases, such as [deep linking](https://developer.xero.com/documentation/api-guides/deep-link-xero). - """ - - supplemental_data: Annotated[ - Optional[SupplementalData], pydantic.Field(alias="supplementalData") - ] = None - r"""Supplemental data is additional data you can include in our standard data types. - - It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. - """ - - tax_number: Annotated[OptionalNullable[str], pydantic.Field(alias="taxNumber")] = ( - UNSET - ) - r"""Company tax number.""" - - web_links: Annotated[ - OptionalNullable[List[Weblink]], pydantic.Field(alias="webLinks") - ] = UNSET - r"""An array of weblinks.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "accountingPlatformRef", - "addresses", - "baseCurrency", - "companyLegalName", - "companyName", - "createdDate", - "financialYearStartDate", - "ledgerLockDate", - "phoneNumbers", - "registrationNumber", - "sourceUrls", - "supplementalData", - "taxNumber", - "webLinks", - ] - ) - nullable_fields = set( - [ - "accountingPlatformRef", - "addresses", - "baseCurrency", - "companyLegalName", - "companyName", - "phoneNumbers", - "registrationNumber", - "sourceUrls", - "taxNumber", - "webLinks", - ] - ) - 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 +from enum import Enum -try: - AccountingAddress.model_rebuild() -except NameError: - pass -try: - CompanyInformation.model_rebuild() -except NameError: - pass +from codat_sync_for_expenses.models._compat.companyinformation import CompanyInformationSchemasType diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/companyreference.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/companyreference.py index 077fa49a6..a40f718b7 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/companyreference.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/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_expenses.types import BaseModel, UNSET_SENTINEL -from pydantic import model_serializer -from typing import Dict, Optional -from typing_extensions import NotRequired, TypedDict +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.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="The name of the company") + description: Optional[str] = Field(default=None, description="A description of the property.") + 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): - description: NotRequired[str] - r"""Additional information about the company. This can be used to store foreign IDs, references, etc.""" - id: NotRequired[str] - r"""Unique identifier for your SMB in Codat.""" - links: NotRequired[CompanyReferenceLinksTypedDict] - r"""A collection of links for the company.""" - name: NotRequired[str] - r"""The name of 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): - description: Optional[str] = None - r"""Additional information about the company. This can be used to store foreign IDs, references, etc.""" + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - id: Optional[str] = None - r"""Unique identifier for your SMB in Codat.""" + * `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([ + ]) - links: Optional[CompanyReferenceLinks] = None - r"""A collection of links for the company.""" + _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 - name: Optional[str] = None - r"""The name of 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(["description", "id", "links", "name", "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-expenses/src/codat_sync_for_expenses/models/shared/companyrequestbody.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/companyrequestbody.py index ffbe905fa..0576c940e 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/companyrequestbody.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/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_expenses.types import BaseModel, UNSET_SENTINEL -from pydantic import model_serializer -from typing import Dict, Optional -from typing_extensions import NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -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: prealpha + Contact: expenses@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-expenses/src/codat_sync_for_expenses/models/shared/companysyncstatus.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/companysyncstatus.py index 8be3cc0d2..eb50f9f20 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/companysyncstatus.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/companysyncstatus.py @@ -1,157 +1,139 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_expenses.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 +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class CompanySyncStatusTypedDict(TypedDict): - company_id: NotRequired[Nullable[str]] - r"""Unique identifier for your SMB in Codat.""" - data_pushed: NotRequired[bool] - r"""Boolean of whether the sync resulted in data being pushed.""" - error_message: NotRequired[Nullable[str]] - r"""Error message of the sync.""" - sync_exception_message: NotRequired[Nullable[str]] - r"""Exception message of the sync.""" - sync_id: NotRequired[Nullable[str]] - r"""Unique identifier of the sync.""" - sync_status: NotRequired[Nullable[str]] - r"""Text status of the sync.""" - sync_status_code: NotRequired[int] - r"""Status code of the sync.""" - sync_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. - """ + The version of the OpenAPI document: prealpha + Contact: expenses@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 + +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL class CompanySyncStatus(BaseModel): - company_id: Annotated[OptionalNullable[str], pydantic.Field(alias="companyId")] = ( - UNSET + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'companyId', 'company_id', 'errorMessage', 'error_message', 'syncExceptionMessage', 'syncId', 'syncStatus', 'sync_exception_message', 'sync_id', 'sync_status'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + CompanySyncStatus + """ # noqa: E501 + company_id: OptionalNullable[str] = Field(default=UNSET, description="Unique identifier for your SMB in Codat.", alias="companyId") + sync_id: OptionalNullable[str] = Field(default=UNSET, description="Unique identifier of the sync.", alias="syncId") + sync_status_code: Optional[int] = Field(default=None, description="Status code of the sync.", alias="syncStatusCode") + sync_status: OptionalNullable[str] = Field(default=UNSET, description="Text status of the sync.", alias="syncStatus") + error_message: OptionalNullable[str] = Field(default=UNSET, description="Error message of the sync.", alias="errorMessage") + sync_exception_message: OptionalNullable[str] = Field(default=UNSET, description="Exception message of the sync.", alias="syncExceptionMessage") + sync_utc: Optional[str] = Field(default=None, description="Datetime of the sync.", alias="syncUtc") + data_pushed: Optional[bool] = Field(default=None, description="Boolean of whether the sync resulted in data being pushed.", alias="dataPushed") + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["companyId", "syncId", "syncStatusCode", "syncStatus", "errorMessage", "syncExceptionMessage", "syncUtc", "dataPushed"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), ) - r"""Unique identifier for your SMB in Codat.""" - data_pushed: Annotated[Optional[bool], pydantic.Field(alias="dataPushed")] = None - r"""Boolean of whether the sync resulted in data being pushed.""" - error_message: Annotated[ - OptionalNullable[str], pydantic.Field(alias="errorMessage") - ] = UNSET - r"""Error message of the sync.""" + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - sync_exception_message: Annotated[ - OptionalNullable[str], pydantic.Field(alias="syncExceptionMessage") - ] = UNSET - r"""Exception message of the sync.""" + 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()) - sync_id: Annotated[OptionalNullable[str], pydantic.Field(alias="syncId")] = UNSET - r"""Unique identifier of the sync.""" + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CompanySyncStatus from a JSON string""" + return cls.from_dict(json.loads(json_str)) - sync_status: Annotated[ - OptionalNullable[str], pydantic.Field(alias="syncStatus") - ] = UNSET - r"""Text status of the sync.""" + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - sync_status_code: Annotated[ - Optional[int], pydantic.Field(alias="syncStatusCode") - ] = None - r"""Status code of the sync.""" + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - sync_utc: Annotated[Optional[str], pydantic.Field(alias="syncUtc")] = 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: + * `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", + ]) - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + _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 CompanySyncStatus from a dict""" + if obj is None: + return None - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: + if not isinstance(obj, dict): + return cls.model_validate(obj) - - 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` + _obj = cls.model_validate({ + "companyId": obj.get("companyId"), + "syncId": obj.get("syncId"), + "syncStatusCode": obj.get("syncStatusCode"), + "syncStatus": obj.get("syncStatus"), + "errorMessage": obj.get("errorMessage"), + "syncExceptionMessage": obj.get("syncExceptionMessage"), + "syncUtc": obj.get("syncUtc"), + "dataPushed": obj.get("dataPushed") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) - > 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. - """ + return _obj - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "companyId", - "dataPushed", - "errorMessage", - "syncExceptionMessage", - "syncId", - "syncStatus", - "syncStatusCode", - "syncUtc", - ] - ) - nullable_fields = set( - [ - "companyId", - "errorMessage", - "syncExceptionMessage", - "syncId", - "syncStatus", - ] - ) - 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: - CompanySyncStatus.model_rebuild() -except NameError: - pass + + + + +class CompanySyncStatusTypedDict(TypedDict): + """TypedDict variant of CompanySyncStatus, for dict-literal request/response inputs.""" + company_id: NotRequired[Optional[str]] + sync_id: NotRequired[Optional[str]] + sync_status_code: NotRequired[Optional[int]] + sync_status: NotRequired[Optional[str]] + error_message: NotRequired[Optional[str]] + sync_exception_message: NotRequired[Optional[str]] + sync_utc: NotRequired[Optional[str]] + data_pushed: NotRequired[Optional[bool]] + additional_properties: NotRequired[Dict[str, Any]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/companyupdaterequest.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/companyupdaterequest.py index a54c3cd6d..ccb96eefd 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/companyupdaterequest.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/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_expenses.types import BaseModel, UNSET_SENTINEL -from pydantic import model_serializer -from typing import Dict, Optional -from typing_extensions import NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class CompanyUpdateRequestTypedDict(TypedDict): - description: NotRequired[str] - r"""Additional information about the company. This can be used to store foreign IDs, references, etc.""" - name: NotRequired[str] - r"""Name of company being connected.""" - 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: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class CompanyUpdateRequest(BaseModel): - description: Optional[str] = None - r"""Additional information about the company. This can be used to store foreign IDs, references, etc.""" - name: Optional[str] = None - r"""Name of company being connected.""" +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(["description", "name", "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="A description of the property.") + 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-expenses/src/codat_sync_for_expenses/models/shared/connection.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/connection.py index adb64d4b5..4b2304cdf 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/connection.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/connection.py @@ -1,230 +1,168 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from __future__ import annotations -from .dataconnectionerror import DataConnectionError, DataConnectionErrorTypedDict -from .dataconnectionstatus import DataConnectionStatus -from codat_sync_for_expenses.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-expenses-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). - """ - - 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 - ``` +# coding: utf-8 +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - - 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. - """ - id: str - r"""Unique identifier for a company's data connection.""" - integration_id: str - r"""A Codat ID representing the integration.""" - link_url: str - r"""The link URL your customers can use to authorize access to their business application.""" - platform_name: str - r"""Name of integration connected to company.""" - 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.""" - status: DataConnectionStatus - r"""The current authorization status of the data connection.""" - connection_info: NotRequired[Nullable[Dict[str, Any]]] - data_connection_errors: NotRequired[Nullable[List[DataConnectionErrorTypedDict]]] - 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. - """ + Do not edit the class manually. +""" # noqa: E501 +from __future__ import annotations +from codat_sync_for_expenses.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_expenses.models.shared.dataconnectionerror import DataConnectionError, DataConnectionErrorTypedDict +from codat_sync_for_expenses.models.shared.dataconnectionstatus import DataConnectionStatus +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL class Connection(BaseModel): - r"""A connection represents a [company's](https://docs.codat.io/sync-for-expenses-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). - """ - - 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. + @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.""" - - link_url: Annotated[str, pydantic.Field(alias="linkUrl")] - r"""The link URL your customers can use to authorize access to their business application.""" - - platform_name: Annotated[str, pydantic.Field(alias="platformName")] - r"""Name of integration connected to company.""" - - 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.""" - + A connection represents a [company's](https://docs.codat.io/sync-for-expenses-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.""" - - connection_info: Annotated[ - OptionalNullable[Dict[str, Any]], pydantic.Field(alias="connectionInfo") - ] = UNSET - - data_connection_errors: Annotated[ - OptionalNullable[List[DataConnectionError]], - pydantic.Field(alias="dataConnectionErrors"), - ] = UNSET - - 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="Date of the transfer transaction as recorded in the accounting software.", alias="lastSync") + created: str = Field(description="Date of the transfer transaction as recorded in the accounting software.") + 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. - """ - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - ["connectionInfo", "dataConnectionErrors", "integrationKey", "lastSync"] - ) - nullable_fields = set(["connectionInfo", "dataConnectionErrors"]) - 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-expenses/src/codat_sync_for_expenses/models/shared/connections.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/connections.py index 672af0b40..bafbd962b 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/connections.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/connections.py @@ -1,58 +1,124 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.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_expenses.models.shared.connection import Connection, ConnectionTypedDict +from codat_sync_for_expenses.models.shared.links import Links, LinksTypedDict +from typing import Optional, Set +from typing_extensions import Self +class Connections(BaseModel): -class ConnectionsTypedDict(TypedDict): - links: LinksTypedDict - 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.""" - 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): - links: Annotated[Links, pydantic.Field(alias="_links")] - page_number: Annotated[int, pydantic.Field(alias="pageNumber")] - r"""Current page number.""" + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - page_size: Annotated[int, pydantic.Field(alias="pageSize")] - r"""Number of items to return in results array.""" + 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()) - total_results: Annotated[int, pydantic.Field(alias="totalResults")] - r"""Total number of items.""" + @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-expenses/src/codat_sync_for_expenses/models/shared/contact.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/contact.py index 5cea4858f..d86fa8d93 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/contact.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/contact.py @@ -1,119 +1,132 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .customerstatus import CustomerStatus -from .items import Items, ItemsTypedDict -from .phonenumber_items import PhoneNumberItems, PhoneNumberItemsTypedDict -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class ContactTypedDict(TypedDict): - status: CustomerStatus - r"""Status of customer.""" - address: NotRequired[ItemsTypedDict] - email: NotRequired[Nullable[str]] - r"""Email of a contact for a customer.""" - modified_date: 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: +""" + Expenses - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 - 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` +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_expenses.models.shared.customerstatus import CustomerStatus +from codat_sync_for_expenses.models.shared.items import Items, ItemsTypedDict +from codat_sync_for_expenses.models.shared.phonenumber_items import PhoneNumberItems, PhoneNumberItemsTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL +class Contact(BaseModel): - > 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 = {'email', 'name', 'phone'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } """ - name: NotRequired[Nullable[str]] - r"""Name of a contact for a customer.""" - phone: NotRequired[Nullable[List[PhoneNumberItemsTypedDict]]] - r"""An array of Phone numbers.""" - - -class Contact(BaseModel): + Contact + """ # noqa: E501 + name: OptionalNullable[str] = Field(default=UNSET, description="Name of a contact for a customer.") + email: OptionalNullable[str] = Field(default=UNSET, description="Email of a contact for a customer.") + phone: OptionalNullable[List[PhoneNumberItems]] = Field(default=UNSET, description="An array of Phone numbers.") + address: Optional[Items] = Field(default=None, description="An object of Address information.") status: CustomerStatus - r"""Status of customer.""" + modified_date: Optional[str] = Field(default=None, description="Date of the transfer transaction as recorded in the accounting software.", alias="modifiedDate") + __properties: ClassVar[List[str]] = ["name", "email", "phone", "address", "status", "modifiedDate"] + + 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 Contact 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 phone (list) + _items = [] + if self.phone: + for _item_phone in self.phone: + if _item_phone: + _items.append(_item_phone.to_dict()) + _dict['phone'] = _items + # override the default output from pydantic by calling `to_dict()` of address + if self.address: + _dict['address'] = self.address.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Contact 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"), + "email": obj.get("email"), + "phone": [PhoneNumberItems.from_dict(_item) for _item in obj["phone"]] if obj.get("phone") is not None else None, + "address": Items.from_dict(obj["address"]) if obj.get("address") is not None else None, + "status": obj.get("status"), + "modifiedDate": obj.get("modifiedDate") + }) + return _obj - address: Optional[Items] = None - email: OptionalNullable[str] = UNSET - r"""Email of a contact for a customer.""" - modified_date: Annotated[Optional[str], pydantic.Field(alias="modifiedDate")] = 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. - """ - - name: OptionalNullable[str] = UNSET - r"""Name of a contact for a customer.""" - - phone: OptionalNullable[List[PhoneNumberItems]] = UNSET - r"""An array of Phone numbers.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["address", "email", "modifiedDate", "name", "phone"]) - nullable_fields = set(["email", "name", "phone"]) - 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: - Contact.model_rebuild() -except NameError: - pass +class ContactTypedDict(TypedDict): + """TypedDict variant of Contact, for dict-literal request/response inputs.""" + name: NotRequired[Optional[str]] + email: NotRequired[Optional[str]] + phone: NotRequired[Optional[List[PhoneNumberItemsTypedDict]]] + address: NotRequired[Optional[ItemsTypedDict]] + status: CustomerStatus + modified_date: NotRequired[Optional[str]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/createaccountresponse.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/createaccountresponse.py index 82411c23b..741c93916 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/createaccountresponse.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/createaccountresponse.py @@ -1,652 +1,171 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .accountstatus import AccountStatus -from .accounttype import AccountType -from .datatype import DataType -from .pushoperationchange import PushOperationChange, PushOperationChangeTypedDict -from .pushoperationstatus import PushOperationStatus -from .supplementaldata import SupplementalData, SupplementalDataTypedDict -from .validation import Validation, ValidationTypedDict -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from codat_sync_for_expenses.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, deprecated - - -class CreateAccountResponseMetadataTypedDict(TypedDict): - is_deleted: NotRequired[Nullable[bool]] - r"""Indicates whether the record has been deleted in the third-party system this record originated from.""" - - -class CreateAccountResponseMetadata(BaseModel): - is_deleted: Annotated[OptionalNullable[bool], pydantic.Field(alias="isDeleted")] = ( - UNSET - ) - r"""Indicates whether the record has been deleted in the third-party system this record originated from.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["isDeleted"]) - nullable_fields = set(["isDeleted"]) - 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 - - -class CreateAccountResponseValidDataTypeLinksTypedDict(TypedDict): - r"""When querying Codat's data model, some data types return `validDatatypeLinks` metadata in the JSON response. This indicates where that object can be used as a reference—a _valid link_—when creating or updating other data. - - For example, `validDatatypeLinks` might indicate the following references: - - - Which tax rates are valid to use on the line item of a bill. - - Which items can be used when creating an invoice. - - You can use `validDatatypeLinks` to present your SMB customers with only valid choices when selecting objects from a list, for example. - - ## `validDatatypeLinks` example - - The following example uses the `Accounting.Accounts` data type. It shows that, on the linked integration, this account is valid as the account on a payment or bill payment; and as the account referenced on the line item of a direct income or direct cost. Because there is no valid link to Invoices or Bills, using this account on those data types will result in an error. - - ```json validDatatypeLinks for an account - { - \"id\": \"bd9e85e0-0478-433d-ae9f-0b3c4f04bfe4\", - \"nominalCode\": \"090\", - \"name\": \"Business Bank Account\", - #... - \"validDatatypeLinks\": [ - { - \"property\": \"Id\", - \"links\": [ - \"Payment.AccountRef.Id\", - \"BillPayment.AccountRef.Id\", - \"DirectIncome.LineItems.AccountRef.Id\", - \"DirectCost.LineItems.AccountRef.Id\" - ] - } - ] - } - ``` +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - ## Support for `validDatatypeLinks` + Do not edit the class manually. +""" # noqa: E501 - Codat currently supports `validDatatypeLinks` for some data types on our Xero, QuickBooks Online, QuickBooks Desktop, Exact (NL), and Sage Business Cloud integrations. - If you'd like us to extend support to more data types or integrations, suggest or vote for this on our Product Roadmap. - """ - - links: NotRequired[Nullable[List[str]]] - r"""Supported `dataTypes` that the record can be linked to.""" - property: NotRequired[Nullable[str]] - r"""The property from the account that can be linked.""" - - -class CreateAccountResponseValidDataTypeLinks(BaseModel): - r"""When querying Codat's data model, some data types return `validDatatypeLinks` metadata in the JSON response. This indicates where that object can be used as a reference—a _valid link_—when creating or updating other data. - - For example, `validDatatypeLinks` might indicate the following references: - - - Which tax rates are valid to use on the line item of a bill. - - Which items can be used when creating an invoice. - - You can use `validDatatypeLinks` to present your SMB customers with only valid choices when selecting objects from a list, for example. - - ## `validDatatypeLinks` example - - The following example uses the `Accounting.Accounts` data type. It shows that, on the linked integration, this account is valid as the account on a payment or bill payment; and as the account referenced on the line item of a direct income or direct cost. Because there is no valid link to Invoices or Bills, using this account on those data types will result in an error. - - ```json validDatatypeLinks for an account - { - \"id\": \"bd9e85e0-0478-433d-ae9f-0b3c4f04bfe4\", - \"nominalCode\": \"090\", - \"name\": \"Business Bank Account\", - #... - \"validDatatypeLinks\": [ - { - \"property\": \"Id\", - \"links\": [ - \"Payment.AccountRef.Id\", - \"BillPayment.AccountRef.Id\", - \"DirectIncome.LineItems.AccountRef.Id\", - \"DirectCost.LineItems.AccountRef.Id\" - ] - } - ] - } - ``` - - - - ## Support for `validDatatypeLinks` - - Codat currently supports `validDatatypeLinks` for some data types on our Xero, QuickBooks Online, QuickBooks Desktop, Exact (NL), and Sage Business Cloud integrations. - - If you'd like us to extend support to more data types or integrations, suggest or vote for this on our Product Roadmap. - """ - - links: OptionalNullable[List[str]] = UNSET - r"""Supported `dataTypes` that the record can be linked to.""" - - property: OptionalNullable[str] = UNSET - r"""The property from the account that can be linked.""" +from __future__ import annotations +from codat_sync_for_expenses.models.shared.datatype 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_expenses.models.create_account_response_all_of_data import CreateAccountResponseAllOfData +from codat_sync_for_expenses.models.shared.pushoperationchange import PushOperationChange, PushOperationChangeTypedDict +from codat_sync_for_expenses.models.shared.pushoperationstatus import PushOperationStatus +from codat_sync_for_expenses.models.shared.validation import Validation, ValidationTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL +class CreateAccountResponse(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["links", "property"]) - nullable_fields = set(["links", "property"]) + 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 - - -@deprecated( - "warning: ** DEPRECATED ** - This will be removed in a future release, please migrate away from it as soon as possible." -) -class AccountingAccountTypedDict(TypedDict): - r"""> **Language tip:** Accounts are also referred to as **chart of accounts**, **nominal accounts**, and **general ledger**. - - ## Overview - - Accounts are the categories a business uses to record accounting transactions. From the Accounts endpoints, you can retrieve a list of all accounts for a specified company. - - The categories for an account include: - * Asset - * Expense - * Income - * Liability - * Equity. - - The same account may have a different category based on the integration it is used in. For example, a current account (known as checking in the US) should be categorized as `Asset.Current` for Xero, and `Asset.Bank.Checking` for QuickBooks Online. - - At the same time, each integration may have its own requirements to the categories. For example, a Paypal account in Xero is of the `Asset.Bank` category and therefore requires additional properties to be provided. - - To determine the list of allowed categories for a specific integration, you can: - - Follow our [Create, update, delete data](https://docs.codat.io/using-the-api/push) guide and use the [Get create account model](https://docs.codat.io/sync-for-expenses-api#/operations/get-create-chartOfAccounts-model). - - Refer to the integration's own documentation. - - > **Accounts with no category** - > - > If an account is pulled from the chart of accounts and its nominal code does not lie within the category layout for the company's accounts, then the **type** is `Unknown`. The **fullyQualifiedCategory** and **fullyQualifiedName** fields return `null`. - > - > This approach gives a true representation of the company's accounts whilst preventing distorting financials such as a company's profit and loss and balance sheet reports. - """ - - 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. - """ - current_balance: NotRequired[Nullable[Decimal]] - r"""Current balance in the account.""" - description: NotRequired[Nullable[str]] - r"""Description for the account.""" - fully_qualified_category: NotRequired[Nullable[str]] - r"""Full category of the account. - - For example, `Liability.Current` or `Income.Revenue`. To determine a list of possible categories for each integration, see our examples, follow our [Create, update, delete data](https://docs.codat.io/using-the-api/push) guide, or refer to the integration's own documentation. - """ - fully_qualified_name: NotRequired[Nullable[str]] - r"""Full name of the account, for example: - - `Cash On Hand` - - `Rents Held In Trust` - - `Fixed Asset` - """ - id: NotRequired[str] - r"""Identifier for the account, unique for the company.""" - is_bank_account: NotRequired[bool] - r"""Confirms whether the account is a bank account or not.""" - metadata: NotRequired[CreateAccountResponseMetadataTypedDict] - modified_date: NotRequired[str] - name: NotRequired[Nullable[str]] - r"""Name of the account.""" - 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.""" - source_modified_date: NotRequired[str] - status: NotRequired[AccountStatus] - r"""Status of the account""" - supplemental_data: NotRequired[SupplementalDataTypedDict] - r"""Supplemental data is additional data you can include in our standard data types. - - It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. - """ - type: NotRequired[AccountType] - r"""Type of account""" - valid_datatype_links: NotRequired[ - Nullable[List[CreateAccountResponseValidDataTypeLinksTypedDict]] - ] - r"""The validDatatypeLinks can be used to determine whether an account can be correctly mapped to another object; for example, accounts with a `type` of `income` might only support being used on an Invoice and Direct Income. For more information, see [Valid Data Type Links](/sync-for-expenses-api#/schemas/ValidDataTypeLinks).""" - - -@deprecated( - "warning: ** DEPRECATED ** - This will be removed in a future release, please migrate away from it as soon as possible." -) -class AccountingAccount(BaseModel): - r"""> **Language tip:** Accounts are also referred to as **chart of accounts**, **nominal accounts**, and **general ledger**. - - ## Overview - - Accounts are the categories a business uses to record accounting transactions. From the Accounts endpoints, you can retrieve a list of all accounts for a specified company. - - The categories for an account include: - * Asset - * Expense - * Income - * Liability - * Equity. - - The same account may have a different category based on the integration it is used in. For example, a current account (known as checking in the US) should be categorized as `Asset.Current` for Xero, and `Asset.Bank.Checking` for QuickBooks Online. - - At the same time, each integration may have its own requirements to the categories. For example, a Paypal account in Xero is of the `Asset.Bank` category and therefore requires additional properties to be provided. - - To determine the list of allowed categories for a specific integration, you can: - - Follow our [Create, update, delete data](https://docs.codat.io/using-the-api/push) guide and use the [Get create account model](https://docs.codat.io/sync-for-expenses-api#/operations/get-create-chartOfAccounts-model). - - Refer to the integration's own documentation. - - > **Accounts with no category** - > - > If an account is pulled from the chart of accounts and its nominal code does not lie within the category layout for the company's accounts, then the **type** is `Unknown`. The **fullyQualifiedCategory** and **fullyQualifiedName** fields return `null`. - > - > This approach gives a true representation of the company's accounts whilst preventing distorting financials such as a company's profit and loss and balance sheet reports. - """ - - 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_. - - ## 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. - """ - - current_balance: Annotated[ - Annotated[ - OptionalNullable[Decimal], - BeforeValidator(validate_decimal), - PlainSerializer(serialize_decimal(False)), - ], - pydantic.Field(alias="currentBalance"), - ] = UNSET - r"""Current balance in the account.""" - - description: OptionalNullable[str] = UNSET - r"""Description for the account.""" - - fully_qualified_category: Annotated[ - OptionalNullable[str], pydantic.Field(alias="fullyQualifiedCategory") - ] = UNSET - r"""Full category of the account. - - For example, `Liability.Current` or `Income.Revenue`. To determine a list of possible categories for each integration, see our examples, follow our [Create, update, delete data](https://docs.codat.io/using-the-api/push) guide, or refer to the integration's own documentation. - """ - - fully_qualified_name: Annotated[ - OptionalNullable[str], pydantic.Field(alias="fullyQualifiedName") - ] = UNSET - r"""Full name of the account, for example: - - `Cash On Hand` - - `Rents Held In Trust` - - `Fixed Asset` - """ - - id: Optional[str] = None - r"""Identifier for the account, unique for the company.""" - - is_bank_account: Annotated[ - Optional[bool], pydantic.Field(alias="isBankAccount") - ] = None - r"""Confirms whether the account is a bank account or not.""" - - metadata: Optional[CreateAccountResponseMetadata] = None - - modified_date: Annotated[Optional[str], pydantic.Field(alias="modifiedDate")] = None - - name: OptionalNullable[str] = UNSET - r"""Name of the account.""" + _nullable = {'changes', 'data', 'errorMessage', 'error_message', 'timeoutInMinutes', 'timeoutInSeconds', 'timeout_in_minutes', 'timeout_in_seconds'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + CreateAccountResponse + """ # noqa: E501 + changes: OptionalNullable[List[PushOperationChange]] = Field(default=UNSET, description="Contains a single entry that communicates which record has changed and the manner in which it changed. ") + data_type: Optional[DataType] = 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="The datetime when the push was requested.", alias="requestedOnUtc") + completed_on_utc: Optional[str] = Field(default=None, description="The datetime when the push was completed, null if Pending.", alias="completedOnUtc") + timeout_in_minutes: OptionalNullable[int] = Field(default=UNSET, description="Number of minutes the push operation must complete within before it times out.", alias="timeoutInMinutes") + timeout_in_seconds: OptionalNullable[int] = Field(default=UNSET, description="Number of seconds the push operation must complete within before it times out.", alias="timeoutInSeconds") + status: PushOperationStatus + error_message: OptionalNullable[str] = Field(default=UNSET, description="A message about the error.", alias="errorMessage") + validation: Optional[Validation] = None + status_code: int = Field(description="Push status code.", alias="statusCode") + data: OptionalNullable[CreateAccountResponseAllOfData] = UNSET + __properties: ClassVar[List[str]] = ["changes", "dataType", "companyId", "pushOperationKey", "dataConnectionKey", "requestedOnUtc", "completedOnUtc", "timeoutInMinutes", "timeoutInSeconds", "status", "errorMessage", "validation", "statusCode", "data"] + + @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=(), + ) - 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.""" - source_modified_date: Annotated[ - Optional[str], pydantic.Field(alias="sourceModifiedDate") - ] = None + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - status: Optional[AccountStatus] = None - r"""Status of the 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()) - supplemental_data: Annotated[ - Optional[SupplementalData], pydantic.Field(alias="supplementalData") - ] = None - r"""Supplemental data is additional data you can include in our standard data types. + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CreateAccountResponse from a JSON string""" + return cls.from_dict(json.loads(json_str)) - It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. - """ + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - type: Optional[AccountType] = None - r"""Type of account""" + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - valid_datatype_links: Annotated[ - OptionalNullable[List[CreateAccountResponseValidDataTypeLinks]], - pydantic.Field(alias="validDatatypeLinks"), - ] = UNSET - r"""The validDatatypeLinks can be used to determine whether an account can be correctly mapped to another object; for example, accounts with a `type` of `income` might only support being used on an Invoice and Direct Income. For more information, see [Valid Data Type Links](/sync-for-expenses-api#/schemas/ValidDataTypeLinks).""" + * `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( - [ - "currency", - "currentBalance", - "description", - "fullyQualifiedCategory", - "fullyQualifiedName", - "id", - "isBankAccount", - "metadata", - "modifiedDate", - "name", - "nominalCode", - "sourceModifiedDate", - "status", - "supplementalData", - "type", - "validDatatypeLinks", - ] - ) - nullable_fields = set( - [ - "currentBalance", - "description", - "fullyQualifiedCategory", - "fullyQualifiedName", - "name", - "nominalCode", - "validDatatypeLinks", - ] + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, ) - serialized = handler(self) - m = {} + # 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() + # override the default output from pydantic by calling `to_dict()` of data + if self.data: + _dict['data'] = self.data.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CreateAccountResponse 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"), + "data": CreateAccountResponseAllOfData.from_dict(obj["data"]) if obj.get("data") is not None else None + }) + return _obj - 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 class CreateAccountResponseTypedDict(TypedDict): - company_id: str - r"""Unique identifier for your SMB in Codat.""" - data_connection_key: str - r"""Unique identifier for a company's data connection.""" - push_operation_key: str - r"""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 - 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. - """ - status: PushOperationStatus - r"""The current status of the push operation.""" - status_code: int - r"""Push status code.""" - changes: NotRequired[Nullable[List[PushOperationChangeTypedDict]]] - r"""Contains a single entry that communicates which record has changed and the manner in which it changed.""" - completed_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. - """ - data: NotRequired[Nullable[AccountingAccountTypedDict]] - data_type: NotRequired[DataType] - r"""Available data types""" - error_message: NotRequired[Nullable[str]] - r"""A message about the error.""" - timeout_in_minutes: NotRequired[Nullable[int]] - r"""Number of minutes the push operation must complete within before it times out.""" - timeout_in_seconds: NotRequired[Nullable[int]] - r"""Number of seconds the push operation must complete within before it times out.""" - validation: NotRequired[ValidationTypedDict] - r"""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.""" - - -class CreateAccountResponse(BaseModel): - company_id: Annotated[str, pydantic.Field(alias="companyId")] - r"""Unique identifier for your SMB in Codat.""" - - data_connection_key: Annotated[str, pydantic.Field(alias="dataConnectionKey")] - r"""Unique identifier for a company's data connection.""" - - push_operation_key: Annotated[str, pydantic.Field(alias="pushOperationKey")] - r"""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: Annotated[str, pydantic.Field(alias="requestedOnUtc")] - 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. - """ - + """TypedDict variant of CreateAccountResponse, for dict-literal request/response inputs.""" + changes: NotRequired[Optional[List[PushOperationChangeTypedDict]]] + data_type: NotRequired[Optional[DataType]] + 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 - r"""The current status of the push operation.""" - - status_code: Annotated[int, pydantic.Field(alias="statusCode")] - r"""Push status code.""" - - changes: OptionalNullable[List[PushOperationChange]] = UNSET - r"""Contains a single entry that communicates which record has changed and the manner in which it changed.""" - - completed_on_utc: Annotated[ - Optional[str], pydantic.Field(alias="completedOnUtc") - ] = 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. - """ - - data: OptionalNullable[AccountingAccount] = UNSET - - data_type: Annotated[Optional[DataType], pydantic.Field(alias="dataType")] = None - r"""Available data types""" - - error_message: Annotated[ - OptionalNullable[str], pydantic.Field(alias="errorMessage") - ] = UNSET - r"""A message about the error.""" - - timeout_in_minutes: Annotated[ - OptionalNullable[int], pydantic.Field(alias="timeoutInMinutes") - ] = UNSET - r"""Number of minutes the push operation must complete within before it times out.""" - - timeout_in_seconds: Annotated[ - OptionalNullable[int], - pydantic.Field( - deprecated="warning: ** DEPRECATED ** - This will be removed in a future release, please migrate away from it as soon as possible.", - alias="timeoutInSeconds", - ), - ] = UNSET - r"""Number of seconds the push operation must complete within before it times out.""" - - validation: Optional[Validation] = None - r"""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.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "changes", - "completedOnUtc", - "data", - "dataType", - "errorMessage", - "timeoutInMinutes", - "timeoutInSeconds", - "validation", - ] - ) - nullable_fields = set( - ["changes", "data", "errorMessage", "timeoutInMinutes", "timeoutInSeconds"] - ) - 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: - CreateAccountResponseMetadata.model_rebuild() -except NameError: - pass -try: - AccountingAccount.model_rebuild() -except NameError: - pass -try: - CreateAccountResponse.model_rebuild() -except NameError: - pass + error_message: NotRequired[Optional[str]] + validation: NotRequired[Optional[ValidationTypedDict]] + status_code: NotRequired[int] + data: NotRequired[Optional[CreateAccountResponseAllOfData]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/createbankaccountresponse.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/createbankaccountresponse.py index bb28cd70d..94e29fde9 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/createbankaccountresponse.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/createbankaccountresponse.py @@ -1,512 +1,10 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - from __future__ import annotations -from .bankaccountstatus import BankAccountStatus -from .datatype import DataType -from .metadata import Metadata, MetadataTypedDict -from .pushoperationchange import PushOperationChange, PushOperationChangeTypedDict -from .pushoperationstatus import PushOperationStatus -from .supplementaldata import SupplementalData, SupplementalDataTypedDict -from .validation import Validation, ValidationTypedDict -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from codat_sync_for_expenses.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 List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict, deprecated class CreateBankAccountResponseBankAccountType(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. - """ - - UNKNOWN = "Unknown" - CREDIT = "Credit" - DEBIT = "Debit" - - -@deprecated( - "warning: ** DEPRECATED ** - This will be removed in a future release, please migrate away from it as soon as possible." -) -class AccountingBankAccountTypedDict(TypedDict): - r"""> **Accessing Bank Accounts through Banking API** - > - > This datatype was originally used for accessing bank account data both in accounting integrations and open banking aggregators. - > - > To view bank account data through the Banking API, please refer to the new [Banking: Account](https://docs.codat.io/sync-for-expenses-api#/schemas/Account) data type. - - ## Overview - - A list of bank accounts associated with a company and a specific data connection. - - Bank accounts data includes: - * The name and ID of the account in the accounting software. - * The currency and balance of the account. - * The sort code and account number. - """ - - account_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. - - FreeAgent integrations - For Credit accounts, only the last four digits are required. For other types, the field is optional. - """ - account_type: NotRequired[CreateBankAccountResponseBankAccountType] - 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. - """ - available_balance: NotRequired[Nullable[Decimal]] - r"""Total available balance of the bank account as reported by the underlying data source. This may take into account overdrafts or pending transactions for example.""" - balance: NotRequired[Nullable[Decimal]] - r"""Balance of the bank 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. - """ - i_ban: NotRequired[Nullable[str]] - r"""International bank account number of the account. Often used when making or receiving international payments.""" - id: NotRequired[str] - r"""Identifier for the account, unique for the company in the accounting software.""" - institution: NotRequired[Nullable[str]] - r"""The institution of the bank account.""" - metadata: NotRequired[MetadataTypedDict] - modified_date: NotRequired[str] - nominal_code: NotRequired[Nullable[str]] - r"""Code used to identify each nominal account for a business.""" - overdraft_limit: NotRequired[Nullable[Decimal]] - r"""Pre-arranged overdraft limit of the account. - - The value is always positive. For example, an overdraftLimit of `1000` means that the balance of the account can go down to `-1000`. - """ - sort_code: NotRequired[Nullable[str]] - r"""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: NotRequired[str] - status: NotRequired[BankAccountStatus] - r"""Status of the bank account.""" - supplemental_data: NotRequired[SupplementalDataTypedDict] - r"""Supplemental data is additional data you can include in our standard data types. - - It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. - """ - - -@deprecated( - "warning: ** DEPRECATED ** - This will be removed in a future release, please migrate away from it as soon as possible." -) -class AccountingBankAccount(BaseModel): - r"""> **Accessing Bank Accounts through Banking API** - > - > This datatype was originally used for accessing bank account data both in accounting integrations and open banking aggregators. - > - > To view bank account data through the Banking API, please refer to the new [Banking: Account](https://docs.codat.io/sync-for-expenses-api#/schemas/Account) data type. - - ## Overview - - A list of bank accounts associated with a company and a specific data connection. - - Bank accounts data includes: - * The name and ID of the account in the accounting software. - * The currency and balance of the account. - * The sort code and account number. - """ - - account_name: Annotated[ - OptionalNullable[str], pydantic.Field(alias="accountName") - ] = UNSET - r"""Name of the bank account in the accounting software.""" - - account_number: Annotated[ - OptionalNullable[str], pydantic.Field(alias="accountNumber") - ] = UNSET - 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. - - FreeAgent integrations - For Credit accounts, only the last four digits are required. For other types, the field is optional. - """ - - account_type: Annotated[ - Optional[CreateBankAccountResponseBankAccountType], - 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. - """ - - available_balance: Annotated[ - Annotated[ - OptionalNullable[Decimal], - BeforeValidator(validate_decimal), - PlainSerializer(serialize_decimal(False)), - ], - pydantic.Field(alias="availableBalance"), - ] = UNSET - r"""Total available balance of the bank account as reported by the underlying data source. This may take into account overdrafts or pending transactions for example.""" - - balance: Annotated[ - OptionalNullable[Decimal], - BeforeValidator(validate_decimal), - PlainSerializer(serialize_decimal(False)), - ] = UNSET - r"""Balance of the bank account.""" - - 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_. - - ## 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. - """ - - i_ban: Annotated[OptionalNullable[str], pydantic.Field(alias="iBan")] = UNSET - r"""International bank account number of the account. Often used when making or receiving international payments.""" - - id: Optional[str] = None - r"""Identifier for the account, unique for the company in the accounting software.""" - - institution: OptionalNullable[str] = UNSET - r"""The institution of the bank account.""" - - metadata: Optional[Metadata] = None - - modified_date: Annotated[Optional[str], pydantic.Field(alias="modifiedDate")] = None - - nominal_code: Annotated[ - OptionalNullable[str], pydantic.Field(alias="nominalCode") - ] = UNSET - r"""Code used to identify each nominal account for a business.""" - - overdraft_limit: Annotated[ - Annotated[ - OptionalNullable[Decimal], - BeforeValidator(validate_decimal), - PlainSerializer(serialize_decimal(False)), - ], - pydantic.Field(alias="overdraftLimit"), - ] = UNSET - r"""Pre-arranged overdraft limit of the account. - - The value is always positive. For example, an overdraftLimit of `1000` means that the balance of the account can go down to `-1000`. - """ - - sort_code: Annotated[OptionalNullable[str], pydantic.Field(alias="sortCode")] = ( - UNSET - ) - r"""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: Annotated[ - Optional[str], pydantic.Field(alias="sourceModifiedDate") - ] = None - - status: Optional[BankAccountStatus] = None - r"""Status of the bank account.""" - - supplemental_data: Annotated[ - Optional[SupplementalData], pydantic.Field(alias="supplementalData") - ] = None - r"""Supplemental data is additional data you can include in our standard data types. - - It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. - """ - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "accountName", - "accountNumber", - "accountType", - "availableBalance", - "balance", - "currency", - "iBan", - "id", - "institution", - "metadata", - "modifiedDate", - "nominalCode", - "overdraftLimit", - "sortCode", - "sourceModifiedDate", - "status", - "supplementalData", - ] - ) - nullable_fields = set( - [ - "accountName", - "accountNumber", - "availableBalance", - "balance", - "iBan", - "institution", - "nominalCode", - "overdraftLimit", - "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 - - -class CreateBankAccountResponseTypedDict(TypedDict): - company_id: str - r"""Unique identifier for your SMB in Codat.""" - data_connection_key: str - r"""Unique identifier for a company's data connection.""" - push_operation_key: str - r"""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 - 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. - """ - status: PushOperationStatus - r"""The current status of the push operation.""" - status_code: int - r"""Push status code.""" - changes: NotRequired[Nullable[List[PushOperationChangeTypedDict]]] - r"""Contains a single entry that communicates which record has changed and the manner in which it changed.""" - completed_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. - """ - data: NotRequired[Nullable[AccountingBankAccountTypedDict]] - data_type: NotRequired[DataType] - r"""Available data types""" - error_message: NotRequired[Nullable[str]] - r"""A message about the error.""" - timeout_in_minutes: NotRequired[Nullable[int]] - r"""Number of minutes the push operation must complete within before it times out.""" - timeout_in_seconds: NotRequired[Nullable[int]] - r"""Number of seconds the push operation must complete within before it times out.""" - validation: NotRequired[ValidationTypedDict] - r"""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.""" - - -class CreateBankAccountResponse(BaseModel): - company_id: Annotated[str, pydantic.Field(alias="companyId")] - r"""Unique identifier for your SMB in Codat.""" - - data_connection_key: Annotated[str, pydantic.Field(alias="dataConnectionKey")] - r"""Unique identifier for a company's data connection.""" - - push_operation_key: Annotated[str, pydantic.Field(alias="pushOperationKey")] - r"""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: Annotated[str, pydantic.Field(alias="requestedOnUtc")] - 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. - """ - - status: PushOperationStatus - r"""The current status of the push operation.""" - - status_code: Annotated[int, pydantic.Field(alias="statusCode")] - r"""Push status code.""" - - changes: OptionalNullable[List[PushOperationChange]] = UNSET - r"""Contains a single entry that communicates which record has changed and the manner in which it changed.""" - - completed_on_utc: Annotated[ - Optional[str], pydantic.Field(alias="completedOnUtc") - ] = 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. - """ - - data: OptionalNullable[AccountingBankAccount] = UNSET - - data_type: Annotated[Optional[DataType], pydantic.Field(alias="dataType")] = None - r"""Available data types""" - - error_message: Annotated[ - OptionalNullable[str], pydantic.Field(alias="errorMessage") - ] = UNSET - r"""A message about the error.""" - - timeout_in_minutes: Annotated[ - OptionalNullable[int], pydantic.Field(alias="timeoutInMinutes") - ] = UNSET - r"""Number of minutes the push operation must complete within before it times out.""" - - timeout_in_seconds: Annotated[ - OptionalNullable[int], - pydantic.Field( - deprecated="warning: ** DEPRECATED ** - This will be removed in a future release, please migrate away from it as soon as possible.", - alias="timeoutInSeconds", - ), - ] = UNSET - r"""Number of seconds the push operation must complete within before it times out.""" - - validation: Optional[Validation] = None - r"""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.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "changes", - "completedOnUtc", - "data", - "dataType", - "errorMessage", - "timeoutInMinutes", - "timeoutInSeconds", - "validation", - ] - ) - nullable_fields = set( - ["changes", "data", "errorMessage", "timeoutInMinutes", "timeoutInSeconds"] - ) - 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: - AccountingBankAccount.model_rebuild() -except NameError: - pass -try: - CreateBankAccountResponse.model_rebuild() -except NameError: - pass + """Speakeasy-name compat for BankAccountType (matched by value set).""" + UNKNOWN = 'Unknown' + CREDIT = 'Credit' + DEBIT = 'Debit' diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/createcustomerresponse.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/createcustomerresponse.py index 9095a4cec..5e680359d 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/createcustomerresponse.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/createcustomerresponse.py @@ -1,417 +1,171 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .contact import Contact, ContactTypedDict -from .customerstatus import CustomerStatus -from .datatype import DataType -from .items import Items, ItemsTypedDict -from .metadata import Metadata, MetadataTypedDict -from .pushoperationchange import PushOperationChange, PushOperationChangeTypedDict -from .pushoperationstatus import PushOperationStatus -from .supplementaldata import SupplementalData, SupplementalDataTypedDict -from .validation import Validation, ValidationTypedDict -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict, deprecated - - -@deprecated( - "warning: ** DEPRECATED ** - This will be removed in a future release, please migrate away from it as soon as possible." -) -class AccountingCustomerTypedDict(TypedDict): - r"""## Overview - - A customer is a person or organisation that buys goods or services. From the Customers endpoints, you can retrieve a [list of all the customers of a company](https://api.codat.io/swagger/index.html#/Customers/get_companies__companyId__data_customers). - - Customers' data links to accounts receivable [invoices](https://docs.codat.io/sync-for-expenses-api#/schemas/Invoice). - - """ - - status: CustomerStatus - r"""Status of customer.""" - addresses: NotRequired[Nullable[List[ItemsTypedDict]]] - r"""An array of Addresses.""" - contact_name: NotRequired[Nullable[str]] - r"""Name of the main contact for the identified customer.""" - contacts: NotRequired[Nullable[List[ContactTypedDict]]] - r"""An array of Contacts.""" - customer_name: NotRequired[Nullable[str]] - r"""Name of the customer as recorded in the accounting system, typically the company name.""" - default_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. - """ - email_address: NotRequired[Nullable[str]] - r"""Email address the customer can be contacted by.""" - id: NotRequired[str] - r"""Identifier for the customer, unique to the company in the accounting software.""" - metadata: NotRequired[MetadataTypedDict] - modified_date: NotRequired[str] - phone: NotRequired[Nullable[str]] - r"""Phone number the customer can be contacted by.""" - registration_number: NotRequired[Nullable[str]] - r"""Company number. In the UK, this is typically the Companies House company registration number.""" - source_modified_date: NotRequired[str] - supplemental_data: NotRequired[SupplementalDataTypedDict] - r"""Supplemental data is additional data you can include in our standard data types. - - It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. - """ - tax_number: NotRequired[Nullable[str]] - r"""Company tax number.""" - - -@deprecated( - "warning: ** DEPRECATED ** - This will be removed in a future release, please migrate away from it as soon as possible." -) -class AccountingCustomer(BaseModel): - r"""## Overview - - A customer is a person or organisation that buys goods or services. From the Customers endpoints, you can retrieve a [list of all the customers of a company](https://api.codat.io/swagger/index.html#/Customers/get_companies__companyId__data_customers). - - Customers' data links to accounts receivable [invoices](https://docs.codat.io/sync-for-expenses-api#/schemas/Invoice). - - """ - - status: CustomerStatus - r"""Status of customer.""" - - addresses: OptionalNullable[List[Items]] = UNSET - r"""An array of Addresses.""" - - contact_name: Annotated[ - OptionalNullable[str], pydantic.Field(alias="contactName") - ] = UNSET - r"""Name of the main contact for the identified customer.""" +""" + Expenses - contacts: OptionalNullable[List[Contact]] = UNSET - r"""An array of Contacts.""" + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | - customer_name: Annotated[ - OptionalNullable[str], pydantic.Field(alias="customerName") - ] = UNSET - r"""Name of the customer as recorded in the accounting system, typically the company name.""" + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - default_currency: Annotated[ - Optional[str], pydantic.Field(alias="defaultCurrency") - ] = None - 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. - - There are only a very small number of edge cases where this currency code is returned by the Codat system. - """ - - email_address: Annotated[ - OptionalNullable[str], pydantic.Field(alias="emailAddress") - ] = UNSET - r"""Email address the customer can be contacted by.""" - - id: Optional[str] = None - r"""Identifier for the customer, unique to the company in the accounting software.""" - - metadata: Optional[Metadata] = None - - modified_date: Annotated[Optional[str], pydantic.Field(alias="modifiedDate")] = None - - phone: OptionalNullable[str] = UNSET - r"""Phone number the customer can be contacted by.""" - - registration_number: Annotated[ - OptionalNullable[str], pydantic.Field(alias="registrationNumber") - ] = UNSET - r"""Company number. In the UK, this is typically the Companies House company registration number.""" - - source_modified_date: Annotated[ - Optional[str], pydantic.Field(alias="sourceModifiedDate") - ] = None - - supplemental_data: Annotated[ - Optional[SupplementalData], pydantic.Field(alias="supplementalData") - ] = None - r"""Supplemental data is additional data you can include in our standard data types. - - It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. - """ - - tax_number: Annotated[OptionalNullable[str], pydantic.Field(alias="taxNumber")] = ( - UNSET - ) - r"""Company tax number.""" +from __future__ import annotations +from codat_sync_for_expenses.models.shared.datatype 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_expenses.models.create_customer_response_all_of_data import CreateCustomerResponseAllOfData +from codat_sync_for_expenses.models.shared.pushoperationchange import PushOperationChange, PushOperationChangeTypedDict +from codat_sync_for_expenses.models.shared.pushoperationstatus import PushOperationStatus +from codat_sync_for_expenses.models.shared.validation import Validation, ValidationTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL +class CreateCustomerResponse(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "addresses", - "contactName", - "contacts", - "customerName", - "defaultCurrency", - "emailAddress", - "id", - "metadata", - "modifiedDate", - "phone", - "registrationNumber", - "sourceModifiedDate", - "supplementalData", - "taxNumber", - ] - ) - nullable_fields = set( - [ - "addresses", - "contactName", - "contacts", - "customerName", - "emailAddress", - "phone", - "registrationNumber", - "taxNumber", - ] - ) + 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 - - -class CreateCustomerResponseTypedDict(TypedDict): - company_id: str - r"""Unique identifier for your SMB in Codat.""" - data_connection_key: str - r"""Unique identifier for a company's data connection.""" - push_operation_key: str - r"""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 - 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. - """ - status: PushOperationStatus - r"""The current status of the push operation.""" - status_code: int - r"""Push status code.""" - changes: NotRequired[Nullable[List[PushOperationChangeTypedDict]]] - r"""Contains a single entry that communicates which record has changed and the manner in which it changed.""" - completed_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. - """ - data: NotRequired[Nullable[AccountingCustomerTypedDict]] - data_type: NotRequired[DataType] - r"""Available data types""" - error_message: NotRequired[Nullable[str]] - r"""A message about the error.""" - timeout_in_minutes: NotRequired[Nullable[int]] - r"""Number of minutes the push operation must complete within before it times out.""" - timeout_in_seconds: NotRequired[Nullable[int]] - r"""Number of seconds the push operation must complete within before it times out.""" - validation: NotRequired[ValidationTypedDict] - r"""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.""" - - -class CreateCustomerResponse(BaseModel): - company_id: Annotated[str, pydantic.Field(alias="companyId")] - r"""Unique identifier for your SMB in Codat.""" - - data_connection_key: Annotated[str, pydantic.Field(alias="dataConnectionKey")] - r"""Unique identifier for a company's data connection.""" - - push_operation_key: Annotated[str, pydantic.Field(alias="pushOperationKey")] - r"""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: Annotated[str, pydantic.Field(alias="requestedOnUtc")] - 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. + _nullable = {'changes', 'data', 'errorMessage', 'error_message', 'timeoutInMinutes', 'timeoutInSeconds', 'timeout_in_minutes', 'timeout_in_seconds'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } """ - + CreateCustomerResponse + """ # noqa: E501 + changes: OptionalNullable[List[PushOperationChange]] = Field(default=UNSET, description="Contains a single entry that communicates which record has changed and the manner in which it changed. ") + data_type: Optional[DataType] = 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="The datetime when the push was requested.", alias="requestedOnUtc") + completed_on_utc: Optional[str] = Field(default=None, description="The datetime when the push was completed, null if Pending.", alias="completedOnUtc") + timeout_in_minutes: OptionalNullable[int] = Field(default=UNSET, description="Number of minutes the push operation must complete within before it times out.", alias="timeoutInMinutes") + timeout_in_seconds: OptionalNullable[int] = Field(default=UNSET, description="Number of seconds the push operation must complete within before it times out.", alias="timeoutInSeconds") status: PushOperationStatus - r"""The current status of the push operation.""" - - status_code: Annotated[int, pydantic.Field(alias="statusCode")] - r"""Push status code.""" - - changes: OptionalNullable[List[PushOperationChange]] = UNSET - r"""Contains a single entry that communicates which record has changed and the manner in which it changed.""" - - completed_on_utc: Annotated[ - Optional[str], pydantic.Field(alias="completedOnUtc") - ] = 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` + error_message: OptionalNullable[str] = Field(default=UNSET, description="A message about the error.", alias="errorMessage") + validation: Optional[Validation] = None + status_code: int = Field(description="Push status code.", alias="statusCode") + data: OptionalNullable[CreateCustomerResponseAllOfData] = UNSET + __properties: ClassVar[List[str]] = ["changes", "dataType", "companyId", "pushOperationKey", "dataConnectionKey", "requestedOnUtc", "completedOnUtc", "timeoutInMinutes", "timeoutInSeconds", "status", "errorMessage", "validation", "statusCode", "data"] + + @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=(), + ) - > 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: OptionalNullable[AccountingCustomer] = UNSET + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - data_type: Annotated[Optional[DataType], pydantic.Field(alias="dataType")] = None - r"""Available data types""" + 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()) - error_message: Annotated[ - OptionalNullable[str], pydantic.Field(alias="errorMessage") - ] = UNSET - r"""A message about the error.""" + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CreateCustomerResponse from a JSON string""" + return cls.from_dict(json.loads(json_str)) - timeout_in_minutes: Annotated[ - OptionalNullable[int], pydantic.Field(alias="timeoutInMinutes") - ] = UNSET - r"""Number of minutes the push operation must complete within before it times out.""" + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - timeout_in_seconds: Annotated[ - OptionalNullable[int], - pydantic.Field( - deprecated="warning: ** DEPRECATED ** - This will be removed in a future release, please migrate away from it as soon as possible.", - alias="timeoutInSeconds", - ), - ] = UNSET - r"""Number of seconds the push operation must complete within before it times out.""" + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - validation: Optional[Validation] = None - r"""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.""" + * `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( - [ - "changes", - "completedOnUtc", - "data", - "dataType", - "errorMessage", - "timeoutInMinutes", - "timeoutInSeconds", - "validation", - ] - ) - nullable_fields = set( - ["changes", "data", "errorMessage", "timeoutInMinutes", "timeoutInSeconds"] + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, ) - serialized = handler(self) - m = {} + # 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() + # override the default output from pydantic by calling `to_dict()` of data + if self.data: + _dict['data'] = self.data.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CreateCustomerResponse 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"), + "data": CreateCustomerResponseAllOfData.from_dict(obj["data"]) if obj.get("data") is not None else None + }) + return _obj - 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: - AccountingCustomer.model_rebuild() -except NameError: - pass -try: - CreateCustomerResponse.model_rebuild() -except NameError: - pass +class CreateCustomerResponseTypedDict(TypedDict): + """TypedDict variant of CreateCustomerResponse, for dict-literal request/response inputs.""" + changes: NotRequired[Optional[List[PushOperationChangeTypedDict]]] + data_type: NotRequired[Optional[DataType]] + 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] + data: NotRequired[Optional[CreateCustomerResponseAllOfData]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/createexpenseresponse.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/createexpenseresponse.py index d2f6dcbf6..a658343eb 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/createexpenseresponse.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/createexpenseresponse.py @@ -1,40 +1,99 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class CreateExpenseResponseTypedDict(TypedDict): - sync_id: NotRequired[str] - r"""Unique id of sync created""" + The version of the OpenAPI document: prealpha + Contact: expenses@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 CreateExpenseResponse(BaseModel): - sync_id: Annotated[Optional[str], pydantic.Field(alias="syncId")] = None - r"""Unique id of sync created""" @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["syncId"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + CreateExpenseResponse + """ # noqa: E501 + sync_id: Optional[str] = Field(default=None, description="Unique id of sync created", alias="syncId") + __properties: ClassVar[List[str]] = ["syncId"] + + 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 CreateExpenseResponse 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: - CreateExpenseResponse.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 CreateExpenseResponse from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "syncId": obj.get("syncId") + }) + return _obj + + + + + +class CreateExpenseResponseTypedDict(TypedDict): + """TypedDict variant of CreateExpenseResponse, for dict-literal request/response inputs.""" + sync_id: NotRequired[Optional[str]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/createreimbursableexpenseresponse.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/createreimbursableexpenseresponse.py index 2bf46f82c..794310994 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/createreimbursableexpenseresponse.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/createreimbursableexpenseresponse.py @@ -1,40 +1,99 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class CreateReimbursableExpenseResponseTypedDict(TypedDict): - sync_id: NotRequired[str] - r"""Unique id of sync created""" + The version of the OpenAPI document: prealpha + Contact: expenses@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 CreateReimbursableExpenseResponse(BaseModel): - sync_id: Annotated[Optional[str], pydantic.Field(alias="syncId")] = None - r"""Unique id of sync created""" @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["syncId"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + CreateReimbursableExpenseResponse + """ # noqa: E501 + sync_id: Optional[str] = Field(default=None, description="Unique id of sync created", alias="syncId") + __properties: ClassVar[List[str]] = ["syncId"] + + 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 CreateReimbursableExpenseResponse 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: - CreateReimbursableExpenseResponse.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 CreateReimbursableExpenseResponse from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "syncId": obj.get("syncId") + }) + return _obj + + + + + +class CreateReimbursableExpenseResponseTypedDict(TypedDict): + """TypedDict variant of CreateReimbursableExpenseResponse, for dict-literal request/response inputs.""" + sync_id: NotRequired[Optional[str]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/createsupplierresponse.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/createsupplierresponse.py index 5726da34c..b4d4aa8bf 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/createsupplierresponse.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/createsupplierresponse.py @@ -1,390 +1,171 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .datatype import DataType -from .items import Items, ItemsTypedDict -from .metadata import Metadata, MetadataTypedDict -from .pushoperationchange import PushOperationChange, PushOperationChangeTypedDict -from .pushoperationstatus import PushOperationStatus -from .supplementaldata import SupplementalData, SupplementalDataTypedDict -from .supplierstatus import SupplierStatus -from .validation import Validation, ValidationTypedDict -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict, deprecated - - -@deprecated( - "warning: ** DEPRECATED ** - This will be removed in a future release, please migrate away from it as soon as possible." -) -class AccountingSupplierTypedDict(TypedDict): - r"""## Overview - - From the **Suppliers** endpoints, you can retrieve a list of [all the suppliers for a company](https://docs.codat.io/sync-for-expenses-api#/operations/list-suppliers). Suppliers' data links to accounts payable [bills](https://docs.codat.io/sync-for-expenses-api#/schemas/Bill). - """ - - status: SupplierStatus - r"""Status of the supplier.""" - addresses: NotRequired[Nullable[List[ItemsTypedDict]]] - r"""An array of Addresses.""" - contact_name: NotRequired[Nullable[str]] - r"""Name of the main contact for the supplier.""" - default_currency: NotRequired[Nullable[str]] - r"""Default currency the supplier's transactional data is recorded in.""" - email_address: NotRequired[Nullable[str]] - r"""Email address that the supplier may be contacted on.""" - id: NotRequired[str] - r"""Identifier for the supplier, unique to the company in the accounting software.""" - metadata: NotRequired[MetadataTypedDict] - modified_date: NotRequired[str] - phone: NotRequired[Nullable[str]] - r"""Phone number that the supplier may be contacted on.""" - registration_number: NotRequired[Nullable[str]] - r"""Company number of the supplier. In the UK, this is typically the company registration number issued by Companies House.""" - source_modified_date: NotRequired[str] - supplemental_data: NotRequired[SupplementalDataTypedDict] - r"""Supplemental data is additional data you can include in our standard data types. - - It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. - """ - supplier_name: NotRequired[Nullable[str]] - r"""Name of the supplier as recorded in the accounting system, typically the company name.""" - tax_number: NotRequired[Nullable[str]] - r"""Supplier's company tax number.""" - - -@deprecated( - "warning: ** DEPRECATED ** - This will be removed in a future release, please migrate away from it as soon as possible." -) -class AccountingSupplier(BaseModel): - r"""## Overview - - From the **Suppliers** endpoints, you can retrieve a list of [all the suppliers for a company](https://docs.codat.io/sync-for-expenses-api#/operations/list-suppliers). Suppliers' data links to accounts payable [bills](https://docs.codat.io/sync-for-expenses-api#/schemas/Bill). - """ - - status: SupplierStatus - r"""Status of the supplier.""" - - addresses: OptionalNullable[List[Items]] = UNSET - r"""An array of Addresses.""" - - contact_name: Annotated[ - OptionalNullable[str], pydantic.Field(alias="contactName") - ] = UNSET - r"""Name of the main contact for the supplier.""" - - default_currency: Annotated[ - OptionalNullable[str], pydantic.Field(alias="defaultCurrency") - ] = UNSET - r"""Default currency the supplier's transactional data is recorded in.""" - - email_address: Annotated[ - OptionalNullable[str], pydantic.Field(alias="emailAddress") - ] = UNSET - r"""Email address that the supplier may be contacted on.""" - - id: Optional[str] = None - r"""Identifier for the supplier, unique to the company in the accounting software.""" - - metadata: Optional[Metadata] = None - - modified_date: Annotated[Optional[str], pydantic.Field(alias="modifiedDate")] = None +""" + Expenses - phone: OptionalNullable[str] = UNSET - r"""Phone number that the supplier may be contacted on.""" + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | - registration_number: Annotated[ - OptionalNullable[str], pydantic.Field(alias="registrationNumber") - ] = UNSET - r"""Company number of the supplier. In the UK, this is typically the company registration number issued by Companies House.""" + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - source_modified_date: Annotated[ - Optional[str], pydantic.Field(alias="sourceModifiedDate") - ] = None + Do not edit the class manually. +""" # noqa: E501 - supplemental_data: Annotated[ - Optional[SupplementalData], pydantic.Field(alias="supplementalData") - ] = None - r"""Supplemental data is additional data you can include in our standard data types. - It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. - """ - - supplier_name: Annotated[ - OptionalNullable[str], pydantic.Field(alias="supplierName") - ] = UNSET - r"""Name of the supplier as recorded in the accounting system, typically the company name.""" - - tax_number: Annotated[OptionalNullable[str], pydantic.Field(alias="taxNumber")] = ( - UNSET - ) - r"""Supplier's company tax number.""" +from __future__ import annotations +from codat_sync_for_expenses.models.shared.datatype 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_expenses.models.create_supplier_response_all_of_data import CreateSupplierResponseAllOfData +from codat_sync_for_expenses.models.shared.pushoperationchange import PushOperationChange, PushOperationChangeTypedDict +from codat_sync_for_expenses.models.shared.pushoperationstatus import PushOperationStatus +from codat_sync_for_expenses.models.shared.validation import Validation, ValidationTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL +class CreateSupplierResponse(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "addresses", - "contactName", - "defaultCurrency", - "emailAddress", - "id", - "metadata", - "modifiedDate", - "phone", - "registrationNumber", - "sourceModifiedDate", - "supplementalData", - "supplierName", - "taxNumber", - ] - ) - nullable_fields = set( - [ - "addresses", - "contactName", - "defaultCurrency", - "emailAddress", - "phone", - "registrationNumber", - "supplierName", - "taxNumber", - ] - ) + 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 - - -class CreateSupplierResponseTypedDict(TypedDict): - company_id: str - r"""Unique identifier for your SMB in Codat.""" - data_connection_key: str - r"""Unique identifier for a company's data connection.""" - push_operation_key: str - r"""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 - 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. + _nullable = {'changes', 'data', 'errorMessage', 'error_message', 'timeoutInMinutes', 'timeoutInSeconds', 'timeout_in_minutes', 'timeout_in_seconds'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } """ + CreateSupplierResponse + """ # noqa: E501 + changes: OptionalNullable[List[PushOperationChange]] = Field(default=UNSET, description="Contains a single entry that communicates which record has changed and the manner in which it changed. ") + data_type: Optional[DataType] = 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="The datetime when the push was requested.", alias="requestedOnUtc") + completed_on_utc: Optional[str] = Field(default=None, description="The datetime when the push was completed, null if Pending.", alias="completedOnUtc") + timeout_in_minutes: OptionalNullable[int] = Field(default=UNSET, description="Number of minutes the push operation must complete within before it times out.", alias="timeoutInMinutes") + timeout_in_seconds: OptionalNullable[int] = Field(default=UNSET, description="Number of seconds the push operation must complete within before it times out.", alias="timeoutInSeconds") status: PushOperationStatus - r"""The current status of the push operation.""" - status_code: int - r"""Push status code.""" - changes: NotRequired[Nullable[List[PushOperationChangeTypedDict]]] - r"""Contains a single entry that communicates which record has changed and the manner in which it changed.""" - completed_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. - """ - data: NotRequired[Nullable[AccountingSupplierTypedDict]] - data_type: NotRequired[DataType] - r"""Available data types""" - error_message: NotRequired[Nullable[str]] - r"""A message about the error.""" - timeout_in_minutes: NotRequired[Nullable[int]] - r"""Number of minutes the push operation must complete within before it times out.""" - timeout_in_seconds: NotRequired[Nullable[int]] - r"""Number of seconds the push operation must complete within before it times out.""" - validation: NotRequired[ValidationTypedDict] - r"""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.""" - - -class CreateSupplierResponse(BaseModel): - company_id: Annotated[str, pydantic.Field(alias="companyId")] - r"""Unique identifier for your SMB in Codat.""" - - data_connection_key: Annotated[str, pydantic.Field(alias="dataConnectionKey")] - r"""Unique identifier for a company's data connection.""" - - push_operation_key: Annotated[str, pydantic.Field(alias="pushOperationKey")] - r"""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: Annotated[str, pydantic.Field(alias="requestedOnUtc")] - 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. - """ - - status: PushOperationStatus - r"""The current status of the push operation.""" - - status_code: Annotated[int, pydantic.Field(alias="statusCode")] - r"""Push status code.""" - - changes: OptionalNullable[List[PushOperationChange]] = UNSET - r"""Contains a single entry that communicates which record has changed and the manner in which it changed.""" - - completed_on_utc: Annotated[ - Optional[str], pydantic.Field(alias="completedOnUtc") - ] = 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` + error_message: OptionalNullable[str] = Field(default=UNSET, description="A message about the error.", alias="errorMessage") + validation: Optional[Validation] = None + status_code: int = Field(description="Push status code.", alias="statusCode") + data: OptionalNullable[CreateSupplierResponseAllOfData] = UNSET + __properties: ClassVar[List[str]] = ["changes", "dataType", "companyId", "pushOperationKey", "dataConnectionKey", "requestedOnUtc", "completedOnUtc", "timeoutInMinutes", "timeoutInSeconds", "status", "errorMessage", "validation", "statusCode", "data"] + + @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=(), + ) - > 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: OptionalNullable[AccountingSupplier] = UNSET + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - data_type: Annotated[Optional[DataType], pydantic.Field(alias="dataType")] = None - r"""Available data types""" + 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()) - error_message: Annotated[ - OptionalNullable[str], pydantic.Field(alias="errorMessage") - ] = UNSET - r"""A message about the error.""" + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of CreateSupplierResponse from a JSON string""" + return cls.from_dict(json.loads(json_str)) - timeout_in_minutes: Annotated[ - OptionalNullable[int], pydantic.Field(alias="timeoutInMinutes") - ] = UNSET - r"""Number of minutes the push operation must complete within before it times out.""" + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - timeout_in_seconds: Annotated[ - OptionalNullable[int], - pydantic.Field( - deprecated="warning: ** DEPRECATED ** - This will be removed in a future release, please migrate away from it as soon as possible.", - alias="timeoutInSeconds", - ), - ] = UNSET - r"""Number of seconds the push operation must complete within before it times out.""" + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - validation: Optional[Validation] = None - r"""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.""" + * `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( - [ - "changes", - "completedOnUtc", - "data", - "dataType", - "errorMessage", - "timeoutInMinutes", - "timeoutInSeconds", - "validation", - ] + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, ) - nullable_fields = set( - ["changes", "data", "errorMessage", "timeoutInMinutes", "timeoutInSeconds"] - ) - serialized = handler(self) - m = {} + # 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() + # override the default output from pydantic by calling `to_dict()` of data + if self.data: + _dict['data'] = self.data.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of CreateSupplierResponse 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"), + "data": CreateSupplierResponseAllOfData.from_dict(obj["data"]) if obj.get("data") is not None else None + }) + return _obj - 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: - AccountingSupplier.model_rebuild() -except NameError: - pass -try: - CreateSupplierResponse.model_rebuild() -except NameError: - pass +class CreateSupplierResponseTypedDict(TypedDict): + """TypedDict variant of CreateSupplierResponse, for dict-literal request/response inputs.""" + changes: NotRequired[Optional[List[PushOperationChangeTypedDict]]] + data_type: NotRequired[Optional[DataType]] + 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] + data: NotRequired[Optional[CreateSupplierResponseAllOfData]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/customer.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/customer.py index 67d232a8a..6ade19868 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/customer.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/customer.py @@ -1,204 +1,171 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from __future__ import annotations -from .contact import Contact, ContactTypedDict -from .customerstatus import CustomerStatus -from .items import Items, ItemsTypedDict -from .metadata import Metadata, MetadataTypedDict -from .supplementaldata import SupplementalData, SupplementalDataTypedDict -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict +# coding: utf-8 +""" + Expenses -class CustomerTypedDict(TypedDict): - r"""## Overview + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | - A customer is a person or organisation that buys goods or services. From the Customers endpoints, you can retrieve a [list of all the customers of a company](https://api.codat.io/swagger/index.html#/Customers/get_companies__companyId__data_customers). + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - Customers' data links to accounts receivable [invoices](https://docs.codat.io/sync-for-expenses-api#/schemas/Invoice). - - """ - - status: CustomerStatus - r"""Status of customer.""" - addresses: NotRequired[Nullable[List[ItemsTypedDict]]] - r"""An array of Addresses.""" - contact_name: NotRequired[Nullable[str]] - r"""Name of the main contact for the identified customer.""" - contacts: NotRequired[Nullable[List[ContactTypedDict]]] - r"""An array of Contacts.""" - customer_name: NotRequired[Nullable[str]] - r"""Name of the customer as recorded in the accounting system, typically the company name.""" - default_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. - """ - email_address: NotRequired[Nullable[str]] - r"""Email address the customer can be contacted by.""" - id: NotRequired[str] - r"""Identifier for the customer, unique to the company in the accounting software.""" - metadata: NotRequired[MetadataTypedDict] - modified_date: NotRequired[str] - phone: NotRequired[Nullable[str]] - r"""Phone number the customer can be contacted by.""" - registration_number: NotRequired[Nullable[str]] - r"""Company number. In the UK, this is typically the Companies House company registration number.""" - source_modified_date: NotRequired[str] - supplemental_data: NotRequired[SupplementalDataTypedDict] - r"""Supplemental data is additional data you can include in our standard data types. - - It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. - """ - tax_number: NotRequired[Nullable[str]] - r"""Company tax number.""" + 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_expenses.models.shared.contact import Contact, ContactTypedDict +from codat_sync_for_expenses.models.shared.customerstatus import CustomerStatus +from codat_sync_for_expenses.models.shared.items import Items, ItemsTypedDict +from codat_sync_for_expenses.models.shared.metadata import Metadata, MetadataTypedDict +from codat_sync_for_expenses.models.shared.supplementaldata import SupplementalData, SupplementalDataTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL class Customer(BaseModel): - r"""## Overview - - A customer is a person or organisation that buys goods or services. From the Customers endpoints, you can retrieve a [list of all the customers of a company](https://api.codat.io/swagger/index.html#/Customers/get_companies__companyId__data_customers). - - Customers' data links to accounts receivable [invoices](https://docs.codat.io/sync-for-expenses-api#/schemas/Invoice). + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'addresses', 'contactName', 'contact_name', 'contacts', 'customerName', 'customer_name', 'emailAddress', 'email_address', 'phone', 'registrationNumber', 'registration_number', 'taxNumber', 'tax_number'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } """ + ## Overview A customer is a person or organisation that buys goods or services. From the Customers endpoints, you can retrieve a [list of all the customers of a company](https://api.codat.io/swagger/index.html#/Customers/get_companies__companyId__data_customers). Customers' data links to accounts receivable [invoices](https://docs.codat.io/sync-for-expenses-api#/schemas/Invoice). + """ # noqa: E501 + modified_date: Optional[str] = Field(default=None, description="The date when the record was last fetched from the accounting software, commerce software, or open banking provider and updated in Codat’s data cache. Use it to identify and retrieve records that have changed since your last fetch. For example, filtering `modifiedDate` to today will provide new records updated in Codat today. This date is populated for all data types except for attachments, balance sheets, company information, and profit & loss reports ([read more](https://docs.codat.io/using-the-api/modified-dates#modified-date)). In Codat's data model, dates and times are represented using the ISO 8601 standard.", alias="modifiedDate") + 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 customer, unique to the company in the accounting software.") + customer_name: OptionalNullable[str] = Field(default=UNSET, description="Name of the customer as recorded in the accounting system, typically the company name.", alias="customerName") + contact_name: OptionalNullable[str] = Field(default=UNSET, description="Name of the main contact for the identified customer.", alias="contactName") + email_address: OptionalNullable[str] = Field(default=UNSET, description="Email address the customer can be contacted by.", alias="emailAddress") + default_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.", alias="defaultCurrency") + phone: OptionalNullable[str] = Field(default=UNSET, description="Phone number the customer can be contacted by.") + addresses: OptionalNullable[List[Items]] = Field(default=UNSET, description="An array of Addresses.") + contacts: OptionalNullable[List[Contact]] = Field(default=UNSET, description="An array of Contacts.") + registration_number: OptionalNullable[str] = Field(default=UNSET, description="Company number. In the UK, this is typically the Companies House company registration number.", alias="registrationNumber") + tax_number: OptionalNullable[str] = Field(default=UNSET, description="Company tax number.", alias="taxNumber") + status: CustomerStatus = Field(description="Current state of the customer.") + metadata: Optional[Metadata] = None + supplemental_data: Optional[SupplementalData] = Field(default=None, alias="supplementalData") + __properties: ClassVar[List[str]] = ["modifiedDate", "sourceModifiedDate", "id", "customerName", "contactName", "emailAddress", "defaultCurrency", "phone", "addresses", "contacts", "registrationNumber", "taxNumber", "status", "metadata", "supplementalData"] - status: CustomerStatus - r"""Status of customer.""" - - addresses: OptionalNullable[List[Items]] = UNSET - r"""An array of Addresses.""" - - contact_name: Annotated[ - OptionalNullable[str], pydantic.Field(alias="contactName") - ] = UNSET - r"""Name of the main contact for the identified customer.""" - - contacts: OptionalNullable[List[Contact]] = UNSET - r"""An array of Contacts.""" - - customer_name: Annotated[ - OptionalNullable[str], pydantic.Field(alias="customerName") - ] = UNSET - r"""Name of the customer as recorded in the accounting system, typically the company name.""" - - default_currency: Annotated[ - Optional[str], pydantic.Field(alias="defaultCurrency") - ] = None - 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 + 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. - """ + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - email_address: Annotated[ - OptionalNullable[str], pydantic.Field(alias="emailAddress") - ] = UNSET - r"""Email address the customer can be contacted by.""" + 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()) - id: Optional[str] = None - r"""Identifier for the customer, unique to the company in the accounting software.""" + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Customer from a JSON string""" + return cls.from_dict(json.loads(json_str)) - metadata: Optional[Metadata] = None + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - modified_date: Annotated[Optional[str], pydantic.Field(alias="modifiedDate")] = None + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - phone: OptionalNullable[str] = UNSET - r"""Phone number the customer can be contacted by.""" + * `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([ + ]) - registration_number: Annotated[ - OptionalNullable[str], pydantic.Field(alias="registrationNumber") - ] = UNSET - r"""Company number. In the UK, this is typically the Companies House company registration number.""" + _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 + # override the default output from pydantic by calling `to_dict()` of each item in contacts (list) + _items = [] + if self.contacts: + for _item_contacts in self.contacts: + if _item_contacts: + _items.append(_item_contacts.to_dict()) + _dict['contacts'] = _items + # override the default output from pydantic by calling `to_dict()` of metadata + if self.metadata: + _dict['metadata'] = self.metadata.to_dict() + # override the default output from pydantic by calling `to_dict()` of supplemental_data + if self.supplemental_data: + _dict['supplementalData'] = self.supplemental_data.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Customer from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "modifiedDate": obj.get("modifiedDate"), + "sourceModifiedDate": obj.get("sourceModifiedDate"), + "id": obj.get("id"), + "customerName": obj.get("customerName"), + "contactName": obj.get("contactName"), + "emailAddress": obj.get("emailAddress"), + "defaultCurrency": obj.get("defaultCurrency"), + "phone": obj.get("phone"), + "addresses": [Items.from_dict(_item) for _item in obj["addresses"]] if obj.get("addresses") is not None else None, + "contacts": [Contact.from_dict(_item) for _item in obj["contacts"]] if obj.get("contacts") is not None else None, + "registrationNumber": obj.get("registrationNumber"), + "taxNumber": obj.get("taxNumber"), + "status": obj.get("status"), + "metadata": Metadata.from_dict(obj["metadata"]) if obj.get("metadata") is not None else None, + "supplementalData": SupplementalData.from_dict(obj["supplementalData"]) if obj.get("supplementalData") is not None else None + }) + return _obj - source_modified_date: Annotated[ - Optional[str], pydantic.Field(alias="sourceModifiedDate") - ] = None - supplemental_data: Annotated[ - Optional[SupplementalData], pydantic.Field(alias="supplementalData") - ] = None - r"""Supplemental data is additional data you can include in our standard data types. - It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. - """ - tax_number: Annotated[OptionalNullable[str], pydantic.Field(alias="taxNumber")] = ( - UNSET - ) - r"""Company tax number.""" - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "addresses", - "contactName", - "contacts", - "customerName", - "defaultCurrency", - "emailAddress", - "id", - "metadata", - "modifiedDate", - "phone", - "registrationNumber", - "sourceModifiedDate", - "supplementalData", - "taxNumber", - ] - ) - nullable_fields = set( - [ - "addresses", - "contactName", - "contacts", - "customerName", - "emailAddress", - "phone", - "registrationNumber", - "taxNumber", - ] - ) - 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: - Customer.model_rebuild() -except NameError: - pass +class CustomerTypedDict(TypedDict): + """TypedDict variant of Customer, for dict-literal request/response inputs.""" + modified_date: NotRequired[Optional[str]] + source_modified_date: NotRequired[Optional[str]] + id: NotRequired[Optional[str]] + customer_name: NotRequired[Optional[str]] + contact_name: NotRequired[Optional[str]] + email_address: NotRequired[Optional[str]] + default_currency: NotRequired[Optional[str]] + phone: NotRequired[Optional[str]] + addresses: NotRequired[Optional[List[ItemsTypedDict]]] + contacts: NotRequired[Optional[List[ContactTypedDict]]] + registration_number: NotRequired[Optional[str]] + tax_number: NotRequired[Optional[str]] + status: NotRequired[CustomerStatus] + metadata: NotRequired[Optional[MetadataTypedDict]] + supplemental_data: NotRequired[Optional[SupplementalDataTypedDict]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/customerdetails.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/customerdetails.py index f67f3c27b..6fbb4b608 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/customerdetails.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/customerdetails.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_expenses.types import BaseModel, UNSET_SENTINEL -from pydantic import model_serializer -from typing import Optional -from typing_extensions import NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class CustomerDetailsTypedDict(TypedDict): - id: NotRequired[str] - r"""Identifier for the customer, unique to the company in the accounting software.""" + The version of the OpenAPI document: prealpha + Contact: expenses@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 CustomerDetails(BaseModel): - id: Optional[str] = None - r"""Identifier for the customer, unique to the company in the accounting software.""" @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} + """ + CustomerDetails + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Identifier for the customer, unique to the company 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 CustomerDetails 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 CustomerDetails 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 CustomerDetailsTypedDict(TypedDict): + """TypedDict variant of CustomerDetails, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/customers.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/customers.py index b39ba6717..97348de54 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/customers.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/customers.py @@ -1,58 +1,125 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations -from .customer import Customer, CustomerTypedDict -from .links import Links, LinksTypedDict -from codat_sync_for_expenses.types import BaseModel, Nullable, 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_expenses.models.shared.customer import Customer, CustomerTypedDict +from codat_sync_for_expenses.models.shared.links import Links, LinksTypedDict +from typing import Optional, Set +from typing_extensions import Self +from codat_sync_for_expenses.types import Nullable +class Customers(BaseModel): -class CustomersTypedDict(TypedDict): - links: LinksTypedDict - 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.""" - results: NotRequired[List[Nullable[CustomerTypedDict]]] + @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} + """ + Customers + """ # 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[Nullable[Customer]]] = None + __properties: ClassVar[List[str]] = ["pageNumber", "pageSize", "totalResults", "_links", "results"] + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) -class Customers(BaseModel): - links: Annotated[Links, pydantic.Field(alias="_links")] - page_number: Annotated[int, pydantic.Field(alias="pageNumber")] - r"""Current page number.""" + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - page_size: Annotated[int, pydantic.Field(alias="pageSize")] - r"""Number of items to return in results array.""" + 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()) - total_results: Annotated[int, pydantic.Field(alias="totalResults")] - r"""Total number of items.""" + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Customers from a JSON string""" + return cls.from_dict(json.loads(json_str)) - results: Optional[List[Nullable[Customer]]] = 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 Customers 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": [Customer.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None + }) + return _obj -try: - Customers.model_rebuild() -except NameError: - pass + + + + +class CustomersTypedDict(TypedDict): + """TypedDict variant of Customers, 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[Nullable[CustomerTypedDict]]]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/customerstatus.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/customerstatus.py index 1e060f7bd..1fa2ef789 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/customerstatus.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/customerstatus.py @@ -1,12 +1,39 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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 CustomerStatus(str, Enum): - r"""Status of customer.""" + """ + Status of customer. + """ + + """ + allowed enum values + """ + UNKNOWN = 'Unknown' + ACTIVE = 'Active' + ARCHIVED = 'Archived' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of CustomerStatus from a JSON string""" + return cls(json.loads(json_str)) + - UNKNOWN = "Unknown" - ACTIVE = "Active" - ARCHIVED = "Archived" diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/dataconnectionerror.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/dataconnectionerror.py index 4a5995981..2638e37e2 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/dataconnectionerror.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/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_expenses.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): - 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 - ``` - - - - 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. - """ - 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 - ``` +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + The version of the OpenAPI document: prealpha + Contact: expenses@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.""" - 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.""" +from __future__ import annotations +from codat_sync_for_expenses.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_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL class DataConnectionError(BaseModel): - 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="Date of the transfer transaction as recorded in the accounting software.", 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="The datetime in Utc that the error was resolved.", 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)) - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: + 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()) - - 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` + @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)) - > 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. - """ + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - 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: + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + * `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 DataConnectionError from a dict""" + if obj is None: + return None - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: + if not isinstance(obj, dict): + return cls.model_validate(obj) - - 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` + _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 - > 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: OptionalNullable[ErrorStatus] = UNSET - r"""The current status of a transient error. Null statuses indicate that the error is not transient.""" - 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.""" - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "errorMessage", - "erroredOnUtc", - "resolvedOnUtc", - "status", - "statusCode", - "statusText", - ] - ) - 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-expenses/src/codat_sync_for_expenses/models/shared/dataconnectionstatus.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/dataconnectionstatus.py index a97f7be30..23d32d5cd 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/dataconnectionstatus.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/dataconnectionstatus.py @@ -1,13 +1,40 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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-expenses/src/codat_sync_for_expenses/models/shared/datastatus.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/datastatus.py index c71e3050b..65cff4cb4 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/datastatus.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/datastatus.py @@ -1,160 +1,128 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .status import Status -from codat_sync_for_expenses.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 - - -class DataTypes(str, Enum): - r"""Available data types""" - - 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" - - -class DataStatusTypedDict(TypedDict): - r"""Describes the state of data in the Codat cache for a company and data type""" - - current_status: Status - r"""The current status of the dataset.""" - data_type: DataTypes - r"""Available data types""" - last_successful_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 - ``` +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + The version of the OpenAPI document: prealpha + Contact: expenses@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. - """ - latest_successful_sync_id: NotRequired[str] - r"""Unique identifier for the most recent successful sync of data type.""" - latest_sync_id: NotRequired[str] - r"""Unique identifier for most recent sync of data type.""" + Do not edit the class manually. +""" # noqa: E501 +from __future__ import annotations +from codat_sync_for_expenses.models.current_status import CurrentStatus +from codat_sync_for_expenses.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 + +from codat_sync_for_expenses.models.shared.status import Status class DataStatus(BaseModel): - r"""Describes the state of data in the Codat cache for a company and data type""" - current_status: Annotated[Status, pydantic.Field(alias="currentStatus")] - r"""The current status of the dataset.""" + @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: DataTypes = Field(description="Available data types", alias="dataType") + last_successful_sync: Optional[str] = Field(default=None, description="Date of the transfer transaction as recorded in the accounting software.", alias="lastSuccessfulSync") + current_status: Status = 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=(), + ) - data_type: Annotated[DataTypes, pydantic.Field(alias="dataType")] - r"""Available data types""" - last_successful_sync: Annotated[ - Optional[str], pydantic.Field(alias="lastSuccessfulSync") - ] = 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_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + 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. - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - - 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` + * `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([ + ]) - > 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. - """ + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict - latest_successful_sync_id: Annotated[ - Optional[str], pydantic.Field(alias="latestSuccessfulSyncId") - ] = None - r"""Unique identifier for the most recent successful sync of data type.""" + @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 - latest_sync_id: Annotated[Optional[str], pydantic.Field(alias="latestSyncId")] = ( - None - ) - r"""Unique identifier for most recent sync of data type.""" + if not isinstance(obj, dict): + return cls.model_validate(obj) - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - ["lastSuccessfulSync", "latestSuccessfulSyncId", "latestSyncId"] - ) - serialized = handler(self) - m = {} + _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 - 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: - DataStatus.model_rebuild() -except NameError: - pass +class DataStatusTypedDict(TypedDict): + """TypedDict variant of DataStatus, for dict-literal request/response inputs.""" + data_type: NotRequired[DataTypes] + last_successful_sync: NotRequired[Optional[str]] + current_status: NotRequired[Status] + latest_sync_id: NotRequired[Optional[str]] + latest_successful_sync_id: NotRequired[Optional[str]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/datatype.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/datatype.py index e0aff6fb8..a8eac379e 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/datatype.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/datatype.py @@ -1,52 +1,94 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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): - r"""Available data types""" - - 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" + """ + Available data types + """ + + """ + allowed enum values + """ + 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_MINUS_ACCOUNT_BALANCES = 'banking-accountBalances' + BANKING_ACCOUNT_BALANCES = 'banking-accountBalances' + BANKING_MINUS_ACCOUNTS = 'banking-accounts' + BANKING_ACCOUNTS = 'banking-accounts' + BANKING_MINUS_TRANSACTION_CATEGORIES = 'banking-transactionCategories' + BANKING_TRANSACTION_CATEGORIES = 'banking-transactionCategories' + BANKING_MINUS_TRANSACTIONS = 'banking-transactions' + BANKING_TRANSACTIONS = 'banking-transactions' + COMMERCE_MINUS_COMPANY_INFO = 'commerce-companyInfo' + COMMERCE_COMPANY_INFO = 'commerce-companyInfo' + COMMERCE_MINUS_CUSTOMERS = 'commerce-customers' + COMMERCE_CUSTOMERS = 'commerce-customers' + COMMERCE_MINUS_DISPUTES = 'commerce-disputes' + COMMERCE_DISPUTES = 'commerce-disputes' + COMMERCE_MINUS_LOCATIONS = 'commerce-locations' + COMMERCE_LOCATIONS = 'commerce-locations' + COMMERCE_MINUS_ORDERS = 'commerce-orders' + COMMERCE_ORDERS = 'commerce-orders' + COMMERCE_MINUS_PAYMENT_METHODS = 'commerce-paymentMethods' + COMMERCE_PAYMENT_METHODS = 'commerce-paymentMethods' + COMMERCE_MINUS_PAYMENTS = 'commerce-payments' + COMMERCE_PAYMENTS = 'commerce-payments' + COMMERCE_MINUS_PRODUCT_CATEGORIES = 'commerce-productCategories' + COMMERCE_PRODUCT_CATEGORIES = 'commerce-productCategories' + COMMERCE_MINUS_PRODUCTS = 'commerce-products' + COMMERCE_PRODUCTS = 'commerce-products' + COMMERCE_MINUS_TAX_COMPONENTS = 'commerce-taxComponents' + COMMERCE_TAX_COMPONENTS = 'commerce-taxComponents' + COMMERCE_MINUS_TRANSACTIONS = 'commerce-transactions' + + COMMERCE_TRANSACTIONS = 'commerce-transactions' + @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-expenses/src/codat_sync_for_expenses/models/shared/errorvalidation.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/errorvalidation.py index 55a5104a4..a65b29d49 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/errorvalidation.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/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_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from pydantic import model_serializer -from typing import List -from typing_extensions import NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -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: prealpha + Contact: expenses@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_expenses.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_expenses.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-expenses/src/codat_sync_for_expenses/models/shared/errorvalidationitem.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/errorvalidationitem.py index 657f053b2..453845704 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/errorvalidationitem.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/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_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -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: prealpha + Contact: expenses@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_expenses.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-expenses/src/codat_sync_for_expenses/models/shared/expensecontactref.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/expensecontactref.py index 7cc271ef9..8750a56e3 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/expensecontactref.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/expensecontactref.py @@ -1,45 +1,6 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -from enum import Enum -from pydantic import model_serializer -from typing import Optional -from typing_extensions import NotRequired, TypedDict - - -class ExpenseContactRefType(str, Enum): - r"""The type of contact.""" - - SUPPLIER = "Supplier" - -class ExpenseContactRefTypedDict(TypedDict): - id: str - r"""Identifier of supplier or customer.""" - type: NotRequired[ExpenseContactRefType] - r"""The type of contact.""" - - -class ExpenseContactRef(BaseModel): - id: str - r"""Identifier of supplier or customer.""" - - type: Optional[ExpenseContactRefType] = ExpenseContactRefType.SUPPLIER - r"""The type of contact.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["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)) +from enum import Enum - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - return m +from codat_sync_for_expenses.models._compat.expensecontactref import ExpenseContactRefType diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/expensessyncwebhook.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/expensessyncwebhook.py index bf138d637..89b6e49ae 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/expensessyncwebhook.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/expensessyncwebhook.py @@ -1,97 +1,112 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .expensessyncwebhookpayload import ( - ExpensesSyncWebhookPayload, - ExpensesSyncWebhookPayloadTypedDict, -) -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class ExpensesSyncWebhookTypedDict(TypedDict): - event_type: NotRequired[str] - r"""The type of event.""" - generated_date: 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: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + Do not edit the class manually. +""" # noqa: E501 +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_sync_for_expenses.models.shared.expensessyncwebhookpayload import ExpensesSyncWebhookPayload, ExpensesSyncWebhookPayloadTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict - - 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` +class ExpensesSyncWebhook(BaseModel): - > 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) + return {k: v for k, v in serialized.items() if v is not None} """ - id: NotRequired[str] - r"""Unique identifier of the event.""" - payload: NotRequired[ExpensesSyncWebhookPayloadTypedDict] + ExpensesSyncWebhook + """ # 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="The date time in UTC the event was generated in Codat.", alias="generatedDate") + payload: Optional[ExpensesSyncWebhookPayload] = None + __properties: ClassVar[List[str]] = ["id", "eventType", "generatedDate", "payload"] + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) -class ExpensesSyncWebhook(BaseModel): - event_type: Annotated[Optional[str], pydantic.Field(alias="eventType")] = None - r"""The type of event.""" - generated_date: Annotated[Optional[str], pydantic.Field(alias="generatedDate")] = ( - 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_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + 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 ExpensesSyncWebhook 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. - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - - 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` + * `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([ + ]) - > 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. - """ + _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 - id: Optional[str] = None - r"""Unique identifier of the event.""" + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ExpensesSyncWebhook from a dict""" + if obj is None: + return None - payload: Optional[ExpensesSyncWebhookPayload] = None + if not isinstance(obj, dict): + return cls.model_validate(obj) - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["eventType", "generatedDate", "id", "payload"]) - serialized = handler(self) - m = {} + _obj = cls.model_validate({ + "id": obj.get("id"), + "eventType": obj.get("eventType"), + "generatedDate": obj.get("generatedDate"), + "payload": ExpensesSyncWebhookPayload.from_dict(obj["payload"]) if obj.get("payload") is not None else None + }) + 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: - ExpensesSyncWebhook.model_rebuild() -except NameError: - pass +class ExpensesSyncWebhookTypedDict(TypedDict): + """TypedDict variant of ExpensesSyncWebhook, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + event_type: NotRequired[Optional[str]] + generated_date: NotRequired[Optional[str]] + payload: NotRequired[Optional[ExpensesSyncWebhookPayloadTypedDict]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/expensessyncwebhookpayload.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/expensessyncwebhookpayload.py index 90eb8dec7..6338f097b 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/expensessyncwebhookpayload.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/expensessyncwebhookpayload.py @@ -1,50 +1,117 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .companyreference import CompanyReference, CompanyReferenceTypedDict -from .transaction import Transaction, TransactionTypedDict -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class ExpensesSyncWebhookPayloadTypedDict(TypedDict): - reference_company: NotRequired[CompanyReferenceTypedDict] - sync_id: NotRequired[str] - r"""Unique identifier of the sync.""" - transactions: NotRequired[List[TransactionTypedDict]] + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class ExpensesSyncWebhookPayload(BaseModel): - reference_company: Annotated[ - Optional[CompanyReference], pydantic.Field(alias="referenceCompany") - ] = None - sync_id: Annotated[Optional[str], pydantic.Field(alias="syncId")] = None - r"""Unique identifier of the sync.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - transactions: Optional[List[Transaction]] = None +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_sync_for_expenses.models.shared.companyreference import CompanyReference, CompanyReferenceTypedDict +from codat_sync_for_expenses.models.transaction import Transaction, TransactionTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class ExpensesSyncWebhookPayload(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["referenceCompany", "syncId", "transactions"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + ExpensesSyncWebhookPayload + """ # noqa: E501 + reference_company: Optional[CompanyReference] = Field(default=None, alias="referenceCompany") + sync_id: Optional[str] = Field(default=None, description="Unique identifier of the sync.", alias="syncId") + transactions: Optional[List[Transaction]] = None + __properties: ClassVar[List[str]] = ["referenceCompany", "syncId", "transactions"] + + 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 ExpensesSyncWebhookPayload 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: - ExpensesSyncWebhookPayload.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 reference_company + if self.reference_company: + _dict['referenceCompany'] = self.reference_company.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in transactions (list) + _items = [] + if self.transactions: + for _item_transactions in self.transactions: + if _item_transactions: + _items.append(_item_transactions.to_dict()) + _dict['transactions'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ExpensesSyncWebhookPayload from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "referenceCompany": CompanyReference.from_dict(obj["referenceCompany"]) if obj.get("referenceCompany") is not None else None, + "syncId": obj.get("syncId"), + "transactions": [Transaction.from_dict(_item) for _item in obj["transactions"]] if obj.get("transactions") is not None else None + }) + return _obj + + + + + +class ExpensesSyncWebhookPayloadTypedDict(TypedDict): + """TypedDict variant of ExpensesSyncWebhookPayload, for dict-literal request/response inputs.""" + reference_company: NotRequired[Optional[CompanyReferenceTypedDict]] + sync_id: NotRequired[Optional[str]] + transactions: NotRequired[Optional[List[TransactionTypedDict]]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/expensetransaction.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/expensetransaction.py index 6a8603cff..8683b032c 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/expensetransaction.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/expensetransaction.py @@ -1,277 +1,164 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .expensecontactref import ExpenseContactRef, ExpenseContactRefTypedDict -from .expensetransactionline import ( - ExpenseTransactionLine, - ExpenseTransactionLineTypedDict, -) -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from codat_sync_for_expenses.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 List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class BankAccountReferenceTypedDict(TypedDict): - id: NotRequired[str] - r"""Identifier of the bank account.""" - - -class BankAccountReference(BaseModel): - id: Optional[str] = None - r"""Identifier of the bank account.""" +""" + Expenses - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["id"]) - 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 ExpenseTransactionType(str, Enum): - r"""The type of transaction.""" - - PAYMENT = "Payment" - REFUND = "Refund" - REWARD = "Reward" - CHARGEBACK = "Chargeback" - - -class ExpenseTransactionTypedDict(TypedDict): - currency: str - r"""Currency the transaction was recorded in.""" - id: str - r"""Your unique identifier for the transaction.""" - issue_date: 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 API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 - 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. - """ - type: ExpenseTransactionType - r"""The type of transaction.""" - bank_account_ref: NotRequired[BankAccountReferenceTypedDict] - contact_ref: NotRequired[ExpenseContactRefTypedDict] - 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. - - ## 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. | - """ - lines: NotRequired[List[ExpenseTransactionLineTypedDict]] - r"""Array of transaction lines.""" - merchant_name: NotRequired[str] - r"""Name of the merchant where the purchase took place""" - notes: NotRequired[str] - r"""Any private, company notes about the transaction.""" - post_as_draft: NotRequired[Nullable[bool]] - r"""This optional property, when set to true, posts the transaction to a drafted state. Note that postAsDraft is only supported in Microsoft Dynamics 365 Business Central.""" - reference: NotRequired[Nullable[str]] - r"""User-friendly reference for the expense transaction.""" - +from __future__ import annotations +from decimal import Decimal +from codat_sync_for_expenses.utils.serializers import serialize_decimal, validate_decimal +from codat_sync_for_expenses.models.expense_transaction_type import ExpenseTransactionType +import pprint +import re # noqa: F401 +import json + +from pydantic import BeforeValidator, PlainSerializer, BaseModel, ConfigDict, Field, field_validator, model_serializer +from typing import Any, ClassVar, Dict, List, Optional, Union +from typing_extensions import Annotated, NotRequired, TypedDict +from codat_sync_for_expenses.models.bank_account_reference import BankAccountReference, BankAccountReferenceTypedDict +from codat_sync_for_expenses.models.expense_contact_ref import ExpenseContactRef, ExpenseContactRefTypedDict +from codat_sync_for_expenses.models.shared.expensetransactionline import ExpenseTransactionLine, ExpenseTransactionLineTypedDict +from typing import Optional, Set +from typing_extensions import Self +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL class ExpenseTransaction(BaseModel): - currency: str - r"""Currency the transaction was recorded in.""" - - id: str - r"""Your unique identifier for the transaction.""" - - issue_date: Annotated[str, pydantic.Field(alias="issueDate")] - 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. - """ - - type: ExpenseTransactionType - r"""The type of transaction.""" - - bank_account_ref: Annotated[ - Optional[BankAccountReference], pydantic.Field(alias="bankAccountRef") - ] = None - - contact_ref: Annotated[ - Optional[ExpenseContactRef], pydantic.Field(alias="contactRef") - ] = None - - 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 | - - - ### 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. | - """ - - lines: Optional[List[ExpenseTransactionLine]] = None - r"""Array of transaction lines.""" - - merchant_name: Annotated[Optional[str], pydantic.Field(alias="merchantName")] = None - r"""Name of the merchant where the purchase took place""" - - notes: Optional[str] = None - r"""Any private, company notes about the transaction.""" - - post_as_draft: Annotated[ - OptionalNullable[bool], pydantic.Field(alias="postAsDraft") - ] = UNSET - r"""This optional property, when set to true, posts the transaction to a drafted state. Note that postAsDraft is only supported in Microsoft Dynamics 365 Business Central.""" - - reference: OptionalNullable[str] = UNSET - r"""User-friendly reference for the expense transaction.""" @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "bankAccountRef", - "contactRef", - "currencyRate", - "lines", - "merchantName", - "notes", - "postAsDraft", - "reference", - ] - ) - nullable_fields = set(["currencyRate", "postAsDraft", "reference"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + _nullable = {'currencyRate', 'currency_rate', 'postAsDraft', 'post_as_draft', 'reference'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + ExpenseTransaction + """ # noqa: E501 + id: str = Field(description="Your unique identifier for the transaction.") + type: ExpenseTransactionType = Field(description="The type of transaction.") + issue_date: str = Field(description="Date of the transaction was recorded.", alias="issueDate") + currency: str = Field(description="Currency the transaction was recorded in.") + 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") + contact_ref: Optional[ExpenseContactRef] = Field(default=None, description="Supplier or customer for the purchase to be associated to.", alias="contactRef") + bank_account_ref: Optional[BankAccountReference] = Field(default=None, alias="bankAccountRef") + reference: OptionalNullable[str] = Field(default=UNSET, description="User-friendly reference for the expense transaction.") + merchant_name: Optional[str] = Field(default=None, description="Name of the merchant where the purchase took place", alias="merchantName") + lines: Optional[List[ExpenseTransactionLine]] = Field(default=None, description="Array of transaction lines.") + notes: Optional[str] = Field(default=None, description="Any private, company notes about the transaction.") + post_as_draft: OptionalNullable[bool] = Field(default=UNSET, description="This optional property, when set to true, posts the transaction to a drafted state. Note that postAsDraft is only supported in Microsoft Dynamics 365 Business Central.", alias="postAsDraft") + __properties: ClassVar[List[str]] = ["id", "type", "issueDate", "currency", "currencyRate", "contactRef", "bankAccountRef", "reference", "merchantName", "lines", "notes", "postAsDraft"] + + @field_validator('type') + def type_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['Payment', 'Refund', 'Reward', 'Chargeback']): + raise ValueError("must be one of enum values ('Payment', 'Refund', 'Reward', 'Chargeback')") + 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 ExpenseTransaction 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 contact_ref + if self.contact_ref: + _dict['contactRef'] = self.contact_ref.to_dict() + # override the default output from pydantic by calling `to_dict()` of bank_account_ref + if self.bank_account_ref: + _dict['bankAccountRef'] = self.bank_account_ref.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in lines (list) + _items = [] + if self.lines: + for _item_lines in self.lines: + if _item_lines: + _items.append(_item_lines.to_dict()) + _dict['lines'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ExpenseTransaction 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"), + "issueDate": obj.get("issueDate"), + "currency": obj.get("currency"), + "currencyRate": obj.get("currencyRate"), + "contactRef": ExpenseContactRef.from_dict(obj["contactRef"]) if obj.get("contactRef") is not None else None, + "bankAccountRef": BankAccountReference.from_dict(obj["bankAccountRef"]) if obj.get("bankAccountRef") is not None else None, + "reference": obj.get("reference"), + "merchantName": obj.get("merchantName"), + "lines": [ExpenseTransactionLine.from_dict(_item) for _item in obj["lines"]] if obj.get("lines") is not None else None, + "notes": obj.get("notes"), + "postAsDraft": obj.get("postAsDraft") + }) + return _obj - 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: - ExpenseTransaction.model_rebuild() -except NameError: - pass +class ExpenseTransactionTypedDict(TypedDict): + """TypedDict variant of ExpenseTransaction, for dict-literal request/response inputs.""" + id: NotRequired[str] + type: NotRequired[ExpenseTransactionType] + issue_date: NotRequired[str] + currency: NotRequired[str] + currency_rate: NotRequired[Optional[Decimal]] + contact_ref: NotRequired[Optional[ExpenseContactRefTypedDict]] + bank_account_ref: NotRequired[Optional[BankAccountReferenceTypedDict]] + reference: NotRequired[Optional[str]] + merchant_name: NotRequired[Optional[str]] + lines: NotRequired[Optional[List[ExpenseTransactionLineTypedDict]]] + notes: NotRequired[Optional[str]] + post_as_draft: NotRequired[Optional[bool]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/expensetransactionline.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/expensetransactionline.py index 8e44037d2..cb4bdf827 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/expensetransactionline.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/expensetransactionline.py @@ -1,118 +1,148 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations -from .invoiceto import InvoiceTo, InvoiceToTypedDict -from .itemref import ItemRef, ItemRefTypedDict -from .recordref import RecordRef, RecordRefTypedDict -from .trackingref import TrackingRef, TrackingRefTypedDict -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from codat_sync_for_expenses.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 codat_sync_for_expenses.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 Any, ClassVar, Dict, List, Optional, Union from typing_extensions import Annotated, NotRequired, TypedDict +from codat_sync_for_expenses.models.shared.invoiceto import InvoiceTo, InvoiceToTypedDict +from codat_sync_for_expenses.models.shared.itemref import ItemRef, ItemRefTypedDict +from codat_sync_for_expenses.models.shared.recordref import RecordRef, RecordRefTypedDict +from codat_sync_for_expenses.models.shared.trackingref import TrackingRef, TrackingRefTypedDict +from typing import Optional, Set +from typing_extensions import Self + +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL +class ExpenseTransactionLine(BaseModel): + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'invoiceTo', 'invoice_to', 'itemRef', 'item_ref', '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) + } + """ + ExpenseTransactionLine + """ # noqa: E501 + net_amount: Annotated[Decimal, BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(description="Amount of the line, exclusive of tax.", alias="netAmount") + tax_amount: Annotated[Optional[Decimal], BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(default=None, description="Amount of tax for the line.", alias="taxAmount") + tax_rate_ref: Optional[RecordRef] = Field(default=None, alias="taxRateRef") + account_ref: Optional[RecordRef] = Field(default=None, description="The `accountRef` contains the `id` of the account the transaction is against. The `accountRef` object is required for all integrations except QBD which currently supports either itemRef or accountRef.", alias="accountRef") + item_ref: OptionalNullable[ItemRef] = Field(default=UNSET, alias="itemRef") + tracking_refs: OptionalNullable[List[TrackingRef]] = Field(default=UNSET, alias="trackingRefs") + invoice_to: OptionalNullable[InvoiceTo] = Field(default=UNSET, alias="invoiceTo") + __properties: ClassVar[List[str]] = ["netAmount", "taxAmount", "taxRateRef", "accountRef", "itemRef", "trackingRefs", "invoiceTo"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) -class ExpenseTransactionLineTypedDict(TypedDict): - net_amount: Decimal - r"""Amount of the line, exclusive of tax.""" - account_ref: NotRequired[RecordRefTypedDict] - invoice_to: NotRequired[Nullable[InvoiceToTypedDict]] - r"""Unique identifier for the customer billed for the transaction. The `invoiceTo` object is currently supported only for QuickBooks Online and QuickBooks Desktop.""" - item_ref: NotRequired[Nullable[ItemRefTypedDict]] - tax_amount: NotRequired[Decimal] - r"""Amount of tax for the line.""" - tax_rate_ref: NotRequired[RecordRefTypedDict] - tracking_refs: NotRequired[Nullable[List[TrackingRefTypedDict]]] + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) -class ExpenseTransactionLine(BaseModel): - net_amount: Annotated[ - Annotated[ - Decimal, - BeforeValidator(validate_decimal), - PlainSerializer(serialize_decimal(False)), - ], - pydantic.Field(alias="netAmount"), - ] - r"""Amount of the line, exclusive of tax.""" - - account_ref: Annotated[Optional[RecordRef], pydantic.Field(alias="accountRef")] = ( - None - ) + 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()) - invoice_to: Annotated[ - OptionalNullable[InvoiceTo], pydantic.Field(alias="invoiceTo") - ] = UNSET - r"""Unique identifier for the customer billed for the transaction. The `invoiceTo` object is currently supported only for QuickBooks Online and QuickBooks Desktop.""" + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ExpenseTransactionLine from a JSON string""" + return cls.from_dict(json.loads(json_str)) - item_ref: Annotated[OptionalNullable[ItemRef], pydantic.Field(alias="itemRef")] = ( - UNSET - ) + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - tax_amount: Annotated[ - Annotated[ - Optional[Decimal], - BeforeValidator(validate_decimal), - PlainSerializer(serialize_decimal(False)), - ], - pydantic.Field(alias="taxAmount"), - ] = None - r"""Amount of tax for the line.""" - - tax_rate_ref: Annotated[Optional[RecordRef], pydantic.Field(alias="taxRateRef")] = ( - None - ) + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - tracking_refs: Annotated[ - OptionalNullable[List[TrackingRef]], pydantic.Field(alias="trackingRefs") - ] = UNSET + * `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( - [ - "accountRef", - "invoiceTo", - "itemRef", - "taxAmount", - "taxRateRef", - "trackingRefs", - ] + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, ) - nullable_fields = set(["invoiceTo", "itemRef", "trackingRefs"]) - 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: - ExpenseTransactionLine.model_rebuild() -except NameError: - pass + # 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 account_ref + if self.account_ref: + _dict['accountRef'] = self.account_ref.to_dict() + # override the default output from pydantic by calling `to_dict()` of item_ref + if self.item_ref: + _dict['itemRef'] = self.item_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 + # override the default output from pydantic by calling `to_dict()` of invoice_to + if self.invoice_to: + _dict['invoiceTo'] = self.invoice_to.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ExpenseTransactionLine from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "netAmount": obj.get("netAmount"), + "taxAmount": obj.get("taxAmount"), + "taxRateRef": RecordRef.from_dict(obj["taxRateRef"]) if obj.get("taxRateRef") is not None else None, + "accountRef": RecordRef.from_dict(obj["accountRef"]) if obj.get("accountRef") is not None else None, + "itemRef": ItemRef.from_dict(obj["itemRef"]) if obj.get("itemRef") is not None else None, + "trackingRefs": [TrackingRef.from_dict(_item) for _item in obj["trackingRefs"]] if obj.get("trackingRefs") is not None else None, + "invoiceTo": InvoiceTo.from_dict(obj["invoiceTo"]) if obj.get("invoiceTo") is not None else None + }) + return _obj + + + + + +class ExpenseTransactionLineTypedDict(TypedDict): + """TypedDict variant of ExpenseTransactionLine, for dict-literal request/response inputs.""" + net_amount: NotRequired[Decimal] + tax_amount: NotRequired[Optional[Decimal]] + tax_rate_ref: NotRequired[Optional[RecordRefTypedDict]] + account_ref: NotRequired[Optional[RecordRefTypedDict]] + item_ref: NotRequired[Optional[ItemRefTypedDict]] + tracking_refs: NotRequired[Optional[List[TrackingRefTypedDict]]] + invoice_to: NotRequired[Optional[InvoiceToTypedDict]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/halref.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/halref.py index 64c72f6f2..3beb86e8b 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/halref.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/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_expenses.types import BaseModel, UNSET_SENTINEL -from pydantic import model_serializer -from typing import Optional -from typing_extensions import NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class HalRefTypedDict(TypedDict): - href: NotRequired[str] - r"""Uri hypertext reference.""" + The version of the OpenAPI document: prealpha + Contact: expenses@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-expenses/src/codat_sync_for_expenses/models/shared/integrationtype.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/integrationtype.py index 92c91ae17..9591bcbfd 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/integrationtype.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/integrationtype.py @@ -1,11 +1,38 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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 IntegrationType(str, Enum): - r"""Type of transaction that has been processed e.g. Expense or Bank Feed.""" + """ + Type of transaction that has been processed e.g. Expense or Bank Feed. + """ + + """ + allowed enum values + """ + EXPENSES = 'expenses' + BANKFEEDS = 'bankfeeds' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of IntegrationType from a JSON string""" + return cls(json.loads(json_str)) + - EXPENSES = "expenses" - BANKFEEDS = "bankfeeds" diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/invoiceto.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/invoiceto.py index f2c8d3b35..ebd0ad287 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/invoiceto.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/invoiceto.py @@ -1,49 +1,113 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.types import BaseModel, UNSET_SENTINEL -from enum import Enum -from pydantic import model_serializer -from typing import Optional -from typing_extensions import NotRequired, TypedDict +from codat_sync_for_expenses.models.invoice_to_type import InvoiceToType +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 InvoiceToType(str, Enum): - r"""The type of contact.""" +class InvoiceTo(BaseModel): - CUSTOMER = "customer" + @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} + """ + Unique identifier for the customer billed for the transaction. The `invoiceTo` object is currently supported only for QuickBooks Online and QuickBooks Desktop. + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="identifier of customer.") + type: Optional[InvoiceToType] = Field(default=None, description="The type of contact.") + __properties: ClassVar[List[str]] = ["id", "type"] + @field_validator('type') + def type_validate_enum(cls, value): + """Validates the enum""" + if value is None: + return value -class InvoiceToTypedDict(TypedDict): - r"""Unique identifier for the customer billed for the transaction. The `invoiceTo` object is currently supported only for QuickBooks Online and QuickBooks Desktop.""" + if value not in set(['customer']): + raise ValueError("must be one of enum values ('customer')") + return value - id: NotRequired[str] - r"""identifier of customer.""" - type: NotRequired[InvoiceToType] - r"""The type of contact.""" + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) -class InvoiceTo(BaseModel): - r"""Unique identifier for the customer billed for the transaction. The `invoiceTo` object is currently supported only for QuickBooks Online and QuickBooks Desktop.""" + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - id: Optional[str] = None - r"""identifier of customer.""" + 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()) - type: Optional[InvoiceToType] = None - r"""The type of contact.""" + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of InvoiceTo from a JSON string""" + return cls.from_dict(json.loads(json_str)) - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["id", "type"]) - serialized = handler(self) - 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)`: + + * `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 InvoiceTo from a dict""" + if obj is None: + return None - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + if not isinstance(obj, dict): + return cls.model_validate(obj) - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + _obj = cls.model_validate({ + "id": obj.get("id"), + "type": obj.get("type") + }) + return _obj - return m + + + + +class InvoiceToTypedDict(TypedDict): + """TypedDict variant of InvoiceTo, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + type: NotRequired[Optional[InvoiceToType]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/itemref.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/itemref.py index 0a74c2c1e..a8b9214f0 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/itemref.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/itemref.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_expenses.types import BaseModel, UNSET_SENTINEL -from pydantic import model_serializer -from typing import Optional -from typing_extensions import NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class ItemRefTypedDict(TypedDict): - id: NotRequired[str] - r"""Unique identifier for the item associated with the transaction. The `itemRef` object is currently supported only for QuickBooks Desktop. You can specify either `itemRef` or `accountRef`, but not both.""" + The version of the OpenAPI document: prealpha + Contact: expenses@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 ItemRef(BaseModel): - id: Optional[str] = None - r"""Unique identifier for the item associated with the transaction. The `itemRef` object is currently supported only for QuickBooks Desktop. You can specify either `itemRef` or `accountRef`, but not both.""" @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} + """ + ItemRef + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Unique identifier for the item associated with the transaction. The `itemRef` object is currently supported only for QuickBooks Desktop. You can specify either `itemRef` or `accountRef`, but not both.") + __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 ItemRef 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 ItemRef 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 ItemRefTypedDict(TypedDict): + """TypedDict variant of ItemRef, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/items.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/items.py index e137a901f..5fd03d6f1 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/items.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/items.py @@ -1,91 +1,123 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .accountingaddresstype import AccountingAddressType -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class ItemsTypedDict(TypedDict): - type: AccountingAddressType - r"""The type of the address""" - city: NotRequired[Nullable[str]] - r"""City of the customer address.""" - country: NotRequired[Nullable[str]] - r"""Country of the customer address.""" - line1: NotRequired[Nullable[str]] - r"""Line 1 of the customer address.""" - line2: NotRequired[Nullable[str]] - r"""Line 2 of the customer address.""" - postal_code: NotRequired[Nullable[str]] - r"""Postal code or zip code.""" - region: NotRequired[Nullable[str]] - r"""Region of the customer address.""" + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.models.shared.accountingaddresstype import AccountingAddressType +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL class Items(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) + } + """ + Items + """ # noqa: E501 type: AccountingAddressType - 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 customer address.") + 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 Items 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 - city: OptionalNullable[str] = UNSET - r"""City of the customer address.""" + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Items from a dict""" + if obj is None: + return None - country: OptionalNullable[str] = UNSET - r"""Country of the customer address.""" + if not isinstance(obj, dict): + return cls.model_validate(obj) - line1: OptionalNullable[str] = UNSET - r"""Line 1 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 - line2: OptionalNullable[str] = UNSET - r"""Line 2 of the customer address.""" - postal_code: Annotated[ - OptionalNullable[str], pydantic.Field(alias="postalCode") - ] = UNSET - r"""Postal code or zip code.""" - region: OptionalNullable[str] = UNSET - r"""Region of the customer address.""" - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - ["city", "country", "line1", "line2", "postalCode", "region"] - ) - nullable_fields = set( - ["city", "country", "line1", "line2", "postalCode", "region"] - ) - 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: - Items.model_rebuild() -except NameError: - pass + +class ItemsTypedDict(TypedDict): + """TypedDict variant of Items, for dict-literal request/response inputs.""" + type: AccountingAddressType + 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-expenses/src/codat_sync_for_expenses/models/shared/links.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/links.py index 9f51449f6..ab8907713 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/links.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/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_expenses.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class LinksTypedDict(TypedDict): - current: HalRefTypedDict - self_: HalRefTypedDict - next: NotRequired[HalRefTypedDict] - previous: NotRequired[HalRefTypedDict] + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class Links(BaseModel): - current: HalRef - self_: Annotated[HalRef, pydantic.Field(alias="self")] +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_expenses.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-expenses/src/codat_sync_for_expenses/models/shared/mappingoptions.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/mappingoptions.py index f1a27e9dd..7ffab4b01 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/mappingoptions.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/mappingoptions.py @@ -1,89 +1,151 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .accountmappinginfo import AccountMappingInfo, AccountMappingInfoTypedDict -from .taxratemappinginfo import TaxRateMappingInfo, TaxRateMappingInfoTypedDict -from .trackingcategorymappinginfo import ( - TrackingCategoryMappingInfo, - TrackingCategoryMappingInfoTypedDict, -) -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing import List -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class MappingOptionsTypedDict(TypedDict): - accounts: NotRequired[Nullable[List[AccountMappingInfoTypedDict]]] - r"""Array of available accounts for mapping.""" - expense_provider: NotRequired[Nullable[str]] - r"""Name of the expense integration.""" - tax_rates: NotRequired[Nullable[List[TaxRateMappingInfoTypedDict]]] - r"""Array of available tax rates for mapping.""" - tracking_categories: NotRequired[ - Nullable[List[TrackingCategoryMappingInfoTypedDict]] - ] - r"""Array of available tracking categories for mapping.""" + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class MappingOptions(BaseModel): - accounts: OptionalNullable[List[AccountMappingInfo]] = UNSET - r"""Array of available accounts for mapping.""" - expense_provider: Annotated[ - OptionalNullable[str], pydantic.Field(alias="expenseProvider") - ] = UNSET - r"""Name of the expense integration.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - tax_rates: Annotated[ - OptionalNullable[List[TaxRateMappingInfo]], pydantic.Field(alias="taxRates") - ] = UNSET - r"""Array of available tax rates for mapping.""" +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_sync_for_expenses.models.shared.accountmappinginfo import AccountMappingInfo, AccountMappingInfoTypedDict +from codat_sync_for_expenses.models.shared.taxratemappinginfo import TaxRateMappingInfo, TaxRateMappingInfoTypedDict +from codat_sync_for_expenses.models.shared.trackingcategorymappinginfo import TrackingCategoryMappingInfo, TrackingCategoryMappingInfoTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict - tracking_categories: Annotated[ - OptionalNullable[List[TrackingCategoryMappingInfo]], - pydantic.Field(alias="trackingCategories"), - ] = UNSET - r"""Array of available tracking categories for mapping.""" +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL +class MappingOptions(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - ["accounts", "expenseProvider", "taxRates", "trackingCategories"] - ) - nullable_fields = set( - ["accounts", "expenseProvider", "taxRates", "trackingCategories"] - ) + 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: - MappingOptions.model_rebuild() -except NameError: - pass + _nullable = {'accounts', 'expenseProvider', 'expense_provider', 'taxRates', 'tax_rates', 'trackingCategories', 'tracking_categories'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + MappingOptions + """ # noqa: E501 + expense_provider: OptionalNullable[str] = Field(default=UNSET, description="Name of the expense integration.", alias="expenseProvider") + accounts: OptionalNullable[List[AccountMappingInfo]] = Field(default=UNSET, description="Array of available accounts for mapping.") + tracking_categories: OptionalNullable[List[TrackingCategoryMappingInfo]] = Field(default=UNSET, description="Array of available tracking categories for mapping.", alias="trackingCategories") + tax_rates: OptionalNullable[List[TaxRateMappingInfo]] = Field(default=UNSET, description="Array of available tax rates for mapping.", alias="taxRates") + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["expenseProvider", "accounts", "trackingCategories", "taxRates"] + + 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 MappingOptions 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 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 each item in tracking_categories (list) + _items = [] + if self.tracking_categories: + for _item_tracking_categories in self.tracking_categories: + if _item_tracking_categories: + _items.append(_item_tracking_categories.to_dict()) + _dict['trackingCategories'] = _items + # 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 + # 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 MappingOptions from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "expenseProvider": obj.get("expenseProvider"), + "accounts": [AccountMappingInfo.from_dict(_item) for _item in obj["accounts"]] if obj.get("accounts") is not None else None, + "trackingCategories": [TrackingCategoryMappingInfo.from_dict(_item) for _item in obj["trackingCategories"]] if obj.get("trackingCategories") is not None else None, + "taxRates": [TaxRateMappingInfo.from_dict(_item) for _item in obj["taxRates"]] if obj.get("taxRates") is not None else None + }) + # 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 MappingOptionsTypedDict(TypedDict): + """TypedDict variant of MappingOptions, for dict-literal request/response inputs.""" + expense_provider: NotRequired[Optional[str]] + accounts: NotRequired[Optional[List[AccountMappingInfoTypedDict]]] + tracking_categories: NotRequired[Optional[List[TrackingCategoryMappingInfoTypedDict]]] + tax_rates: NotRequired[Optional[List[TaxRateMappingInfoTypedDict]]] + additional_properties: NotRequired[Dict[str, Any]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/metadata.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/metadata.py index 84965e191..e8657969e 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/metadata.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/metadata.py @@ -1,56 +1,104 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class MetadataTypedDict(TypedDict): - is_deleted: NotRequired[Nullable[bool]] - r"""Indicates whether the record has been deleted in the third-party system this record originated from.""" + The version of the OpenAPI document: prealpha + Contact: expenses@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 + +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL class Metadata(BaseModel): - is_deleted: Annotated[OptionalNullable[bool], pydantic.Field(alias="isDeleted")] = ( - UNSET - ) - r"""Indicates whether the record has been deleted in the third-party system this record originated from.""" @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["isDeleted"]) - nullable_fields = set(["isDeleted"]) + 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: - Metadata.model_rebuild() -except NameError: - pass + _nullable = {'isDeleted', 'is_deleted'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + Metadata + """ # noqa: E501 + is_deleted: OptionalNullable[bool] = Field(default=UNSET, description="Indicates whether the record has been deleted in the third-party system this record originated from.", alias="isDeleted") + __properties: ClassVar[List[str]] = ["isDeleted"] + + 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 Metadata 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 Metadata from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "isDeleted": obj.get("isDeleted") + }) + return _obj + + + + + +class MetadataTypedDict(TypedDict): + """TypedDict variant of Metadata, for dict-literal request/response inputs.""" + is_deleted: NotRequired[Optional[bool]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/phonenumber_items.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/phonenumber_items.py index 3e616f124..e295eb597 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/phonenumber_items.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/phonenumber_items.py @@ -1,63 +1,116 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from enum import Enum -from pydantic import model_serializer -from typing_extensions import NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class Type(str, Enum): - r"""The type of phone number""" + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - PRIMARY = "Primary" - LANDLINE = "Landline" - MOBILE = "Mobile" - FAX = "Fax" - UNKNOWN = "Unknown" + Do not edit the class manually. +""" # noqa: E501 -class PhoneNumberItemsTypedDict(TypedDict): - type: Type - r"""The type of phone number""" - number: NotRequired[Nullable[str]] - r"""A phone number.""" +from __future__ import annotations +from codat_sync_for_expenses.models.phone_number_items_type import PhoneNumberItemsType +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_expenses.models.type import Type +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL class PhoneNumberItems(BaseModel): - type: Type - r"""The type of phone number""" - - number: OptionalNullable[str] = UNSET - r"""A phone number.""" @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["number"]) - nullable_fields = set(["number"]) + 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 = {'number'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + PhoneNumberItems + """ # noqa: E501 + number: OptionalNullable[str] = Field(default=UNSET, description="A phone number.") + type: Type = Field(description="The type of phone number") + __properties: ClassVar[List[str]] = ["number", "type"] + + @field_validator('type') + def type_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['Primary', 'Landline', 'Mobile', 'Fax', 'Unknown']): + raise ValueError("must be one of enum values ('Primary', 'Landline', 'Mobile', 'Fax', '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 PhoneNumberItems 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 PhoneNumberItems from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "number": obj.get("number"), + "type": obj.get("type") + }) + return _obj + + + + + +class PhoneNumberItemsTypedDict(TypedDict): + """TypedDict variant of PhoneNumberItems, for dict-literal request/response inputs.""" + number: NotRequired[Optional[str]] + type: NotRequired[Type] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pulloperation.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pulloperation.py index 3d83ebe9e..5cab2dcd7 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pulloperation.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pulloperation.py @@ -1,225 +1,145 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_expenses.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 DatasetStatus(str, Enum): - r"""The current status of the dataset.""" - - 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" +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class PullOperationTypedDict(TypedDict): - r"""Information about a queued, in progress or completed pull operation. - *Formally called `dataset`* - """ - - company_id: str - r"""Unique identifier of the company associated to this pull operation.""" - connection_id: str - r"""Unique identifier of the connection associated to this pull operation.""" - data_type: str - r"""The data type you are requesting in a pull operation.""" - id: str - r"""Unique identifier of the pull operation.""" - is_completed: bool - r"""`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 - r"""`True` if the pull operation entered an error state.""" - progress: int - r"""An integer signifying the progress of the pull operation.""" - requested: 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. - """ - status: DatasetStatus - r"""The current status of the dataset.""" - completed: 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: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + Do not edit the class manually. +""" # noqa: E501 +from __future__ import annotations +from codat_sync_for_expenses.models.dataset_status import DatasetStatus +import pprint +import re # noqa: F401 +import json - 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. - """ - error_message: NotRequired[Nullable[str]] - r"""A message about a transient or persistent error returned by Codat or the source platform.""" - status_description: NotRequired[Nullable[str]] - r"""Additional information about the dataset status.""" - +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_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL class PullOperation(BaseModel): - r"""Information about a queued, in progress or completed pull operation. - *Formally called `dataset`* - """ - - company_id: Annotated[str, pydantic.Field(alias="companyId")] - r"""Unique identifier of the company associated to this pull operation.""" - - connection_id: Annotated[str, pydantic.Field(alias="connectionId")] - r"""Unique identifier of the connection associated to this pull operation.""" - - data_type: Annotated[str, pydantic.Field(alias="dataType")] - r"""The data type you are requesting in a pull operation.""" - - id: str - r"""Unique identifier of the pull operation.""" - - is_completed: Annotated[bool, pydantic.Field(alias="isCompleted")] - r"""`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: Annotated[bool, pydantic.Field(alias="isErrored")] - r"""`True` if the pull operation entered an error state.""" - - progress: int - r"""An integer signifying the progress of the pull operation.""" - requested: 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. + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'errorMessage', 'error_message', 'statusDescription', 'status_description'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } """ + 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: DatasetStatus = Field(description="The current status of the dataset.") + status_description: OptionalNullable[str] = Field(default=UNSET, description="Additional information about the dataset status.", alias="statusDescription") + error_message: OptionalNullable[str] = Field(default=UNSET, description="A message about a transient or persistent error returned by Codat or the source platform.", alias="errorMessage") + requested: str = Field(description="Date of the transfer transaction as recorded in the accounting software.") + completed: Optional[str] = Field(default=None, description="Date of the transfer transaction as recorded in the accounting software.") + 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 - status: DatasetStatus - r"""The current status of the dataset.""" - - completed: 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. - """ - - error_message: Annotated[ - OptionalNullable[str], pydantic.Field(alias="errorMessage") - ] = UNSET - r"""A message about a transient or persistent error returned by Codat or the source platform.""" - - status_description: Annotated[ - OptionalNullable[str], pydantic.Field(alias="statusDescription") - ] = UNSET - r"""Additional information about the dataset status.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["completed", "errorMessage", "statusDescription"]) - nullable_fields = set(["errorMessage", "statusDescription"]) - 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: - PullOperation.model_rebuild() -except NameError: - pass +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[DatasetStatus] + 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-expenses/src/codat_sync_for_expenses/models/shared/pulloperations.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pulloperations.py index c5be07025..541eb40be 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pulloperations.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pulloperations.py @@ -1,58 +1,124 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations -from .links import Links, LinksTypedDict -from .pulloperation import PullOperation, PullOperationTypedDict -from codat_sync_for_expenses.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_expenses.models.shared.links import Links, LinksTypedDict +from codat_sync_for_expenses.models.shared.pulloperation import PullOperation, PullOperationTypedDict +from typing import Optional, Set +from typing_extensions import Self +class PullOperations(BaseModel): -class PullOperationsTypedDict(TypedDict): - links: LinksTypedDict - 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.""" - results: NotRequired[List[PullOperationTypedDict]] + @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=(), + ) -class PullOperations(BaseModel): - links: Annotated[Links, pydantic.Field(alias="_links")] - page_number: Annotated[int, pydantic.Field(alias="pageNumber")] - r"""Current page number.""" + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - page_size: Annotated[int, pydantic.Field(alias="pageSize")] - r"""Number of items to return in results array.""" + 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()) - total_results: Annotated[int, pydantic.Field(alias="totalResults")] - r"""Total number of items.""" + @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)) - results: Optional[List[PullOperation]] = 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 PullOperations 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": [PullOperation.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None + }) + return _obj -try: - PullOperations.model_rebuild() -except NameError: - pass + + + + +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-expenses/src/codat_sync_for_expenses/models/shared/pushchangetype.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushchangetype.py index 76371e9e3..cb4e0feae 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushchangetype.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushchangetype.py @@ -1,14 +1,40 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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): - r"""Type of change being applied to record in third party platform.""" + """ + 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)) + - UNKNOWN = "Unknown" - CREATED = "Created" - MODIFIED = "Modified" - DELETED = "Deleted" - ATTACHMENT_UPLOADED = "AttachmentUploaded" diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushfieldvalidation.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushfieldvalidation.py index 27f6eab17..8bdb65ab4 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushfieldvalidation.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushfieldvalidation.py @@ -1,58 +1,125 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from pydantic import model_serializer -from typing import Optional -from typing_extensions import NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class PushFieldValidationTypedDict(TypedDict): - details: str - r"""Details on the validation issue.""" - field: NotRequired[str] - r"""Field name that resulted in the validation issue.""" - ref: NotRequired[Nullable[str]] - r"""Unique reference identifier for the validation issue.""" + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class PushFieldValidation(BaseModel): - details: str - r"""Details on the validation issue.""" - field: Optional[str] = None - r"""Field name that resulted in the validation issue.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - ref: OptionalNullable[str] = UNSET - r"""Unique reference identifier for the validation issue.""" +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 + +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL +class PushFieldValidation(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["field", "ref"]) - nullable_fields = set(["ref"]) + 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 = {'ref'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + PushFieldValidation + """ # noqa: E501 + field: Optional[str] = Field(default=None, description="Field name that resulted in the validation issue.", alias="field") + details: str = Field(description="Details on the validation issue.") + ref: OptionalNullable[str] = Field(default=UNSET, description="Unique reference identifier for the validation issue.") + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["field", "details", "ref"] + + 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 PushFieldValidation 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 PushFieldValidation from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "field": obj.get("field"), + "details": obj.get("details"), + "ref": obj.get("ref") + }) + # 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 PushFieldValidationTypedDict(TypedDict): + """TypedDict variant of PushFieldValidation, for dict-literal request/response inputs.""" + field: NotRequired[Optional[str]] + details: NotRequired[str] + ref: NotRequired[Optional[str]] + additional_properties: NotRequired[Dict[str, Any]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushoperation.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushoperation.py index f855a55fe..1a2da2029 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushoperation.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushoperation.py @@ -1,219 +1,164 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .datatype import DataType -from .pushoperationchange import PushOperationChange, PushOperationChangeTypedDict -from .pushoperationstatus import PushOperationStatus -from .validation import Validation, ValidationTypedDict -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict - - -class PushOperationTypedDict(TypedDict): - company_id: str - r"""Unique identifier for your SMB in Codat.""" - data_connection_key: str - r"""Unique identifier for a company's data connection.""" - push_operation_key: str - r"""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 - 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. - """ - status: PushOperationStatus - r"""The current status of the push operation.""" - status_code: int - r"""Push status code.""" - changes: NotRequired[Nullable[List[PushOperationChangeTypedDict]]] - r"""Contains a single entry that communicates which record has changed and the manner in which it changed.""" - completed_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: +""" + Expenses - ``` - 2020-10-08T22:40:50Z - 2021-01-01T00:00:00 - ``` + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + The version of the OpenAPI document: prealpha + Contact: expenses@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. - """ - data_type: NotRequired[DataType] - r"""Available data types""" - error_message: NotRequired[Nullable[str]] - r"""A message about the error.""" - timeout_in_minutes: NotRequired[Nullable[int]] - r"""Number of minutes the push operation must complete within before it times out.""" - timeout_in_seconds: NotRequired[Nullable[int]] - r"""Number of seconds the push operation must complete within before it times out.""" - validation: NotRequired[ValidationTypedDict] - r"""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.""" + Do not edit the class manually. +""" # noqa: E501 +from __future__ import annotations +from codat_sync_for_expenses.models.shared.datatype 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_expenses.models.shared.pushoperationchange import PushOperationChange, PushOperationChangeTypedDict +from codat_sync_for_expenses.models.shared.pushoperationstatus import PushOperationStatus +from codat_sync_for_expenses.models.shared.validation import Validation, ValidationTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL class PushOperation(BaseModel): - company_id: Annotated[str, pydantic.Field(alias="companyId")] - r"""Unique identifier for your SMB in Codat.""" - - data_connection_key: Annotated[str, pydantic.Field(alias="dataConnectionKey")] - r"""Unique identifier for a company's data connection.""" - - push_operation_key: Annotated[str, pydantic.Field(alias="pushOperationKey")] - r"""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: Annotated[str, pydantic.Field(alias="requestedOnUtc")] - 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 = {'changes', 'errorMessage', 'error_message', 'timeoutInMinutes', 'timeoutInSeconds', 'timeout_in_minutes', 'timeout_in_seconds'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } """ - + PushOperation + """ # noqa: E501 + changes: OptionalNullable[List[PushOperationChange]] = Field(default=UNSET, description="Contains a single entry that communicates which record has changed and the manner in which it changed. ") + data_type: Optional[DataType] = 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="The datetime when the push was requested.", alias="requestedOnUtc") + completed_on_utc: Optional[str] = Field(default=None, description="The datetime when the push was completed, null if Pending.", alias="completedOnUtc") + timeout_in_minutes: OptionalNullable[int] = Field(default=UNSET, description="Number of minutes the push operation must complete within before it times out.", alias="timeoutInMinutes") + timeout_in_seconds: OptionalNullable[int] = Field(default=UNSET, description="Number of seconds the push operation must complete within before it times out.", alias="timeoutInSeconds") status: PushOperationStatus - r"""The current status of the push operation.""" - - status_code: Annotated[int, pydantic.Field(alias="statusCode")] - r"""Push status code.""" - - changes: OptionalNullable[List[PushOperationChange]] = UNSET - r"""Contains a single entry that communicates which record has changed and the manner in which it changed.""" - - completed_on_utc: Annotated[ - Optional[str], pydantic.Field(alias="completedOnUtc") - ] = 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. - """ - - data_type: Annotated[Optional[DataType], pydantic.Field(alias="dataType")] = None - r"""Available data types""" + error_message: OptionalNullable[str] = Field(default=UNSET, 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 - error_message: Annotated[ - OptionalNullable[str], pydantic.Field(alias="errorMessage") - ] = UNSET - r"""A message about the error.""" - timeout_in_minutes: Annotated[ - OptionalNullable[int], pydantic.Field(alias="timeoutInMinutes") - ] = UNSET - r"""Number of minutes the push operation must complete within before it times out.""" - timeout_in_seconds: Annotated[ - OptionalNullable[int], - pydantic.Field( - deprecated="warning: ** DEPRECATED ** - This will be removed in a future release, please migrate away from it as soon as possible.", - alias="timeoutInSeconds", - ), - ] = UNSET - r"""Number of seconds the push operation must complete within before it times out.""" - validation: Optional[Validation] = None - r"""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.""" - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "changes", - "completedOnUtc", - "dataType", - "errorMessage", - "timeoutInMinutes", - "timeoutInSeconds", - "validation", - ] - ) - nullable_fields = set( - ["changes", "errorMessage", "timeoutInMinutes", "timeoutInSeconds"] - ) - 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: - PushOperation.model_rebuild() -except NameError: - pass +class PushOperationTypedDict(TypedDict): + """TypedDict variant of PushOperation, for dict-literal request/response inputs.""" + changes: NotRequired[Optional[List[PushOperationChangeTypedDict]]] + data_type: NotRequired[Optional[DataType]] + 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-expenses/src/codat_sync_for_expenses/models/shared/pushoperationchange.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushoperationchange.py index 70f193c69..048c72775 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushoperationchange.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushoperationchange.py @@ -1,69 +1,115 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .pushchangetype import PushChangeType -from .pushoperationref import PushOperationRef, PushOperationRefTypedDict -from codat_sync_for_expenses.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 +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class PushOperationChangeTypedDict(TypedDict): - attachment_id: NotRequired[Nullable[str]] - r"""Unique identifier for the attachment created otherwise null.""" - record_ref: NotRequired[PushOperationRefTypedDict] - type: NotRequired[PushChangeType] - r"""Type of change being applied to record in third party platform.""" + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class PushOperationChange(BaseModel): - attachment_id: Annotated[ - OptionalNullable[str], pydantic.Field(alias="attachmentId") - ] = UNSET - r"""Unique identifier for the attachment created otherwise null.""" - record_ref: Annotated[ - Optional[PushOperationRef], pydantic.Field(alias="recordRef") - ] = None +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - type: Optional[PushChangeType] = None - r"""Type of change being applied to record in third party platform.""" +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_sync_for_expenses.models.shared.pushchangetype import PushChangeType +from codat_sync_for_expenses.models.shared.pushoperationref import PushOperationRef, PushOperationRefTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL +class PushOperationChange(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["attachmentId", "recordRef", "type"]) - nullable_fields = set(["attachmentId"]) + 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: - PushOperationChange.model_rebuild() -except NameError: - pass + _nullable = {'attachmentId', 'attachment_id'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + PushOperationChange + """ # noqa: E501 + type: Optional[PushChangeType] = None + record_ref: Optional[PushOperationRef] = Field(default=None, alias="recordRef") + attachment_id: OptionalNullable[str] = Field(default=UNSET, 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-expenses/src/codat_sync_for_expenses/models/shared/pushoperationref.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushoperationref.py index 6fff163b0..2dd2cf040 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushoperationref.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushoperationref.py @@ -1,46 +1,127 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .datatype import DataType -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class PushOperationRefTypedDict(TypedDict): - data_type: NotRequired[DataType] - r"""Available data types""" - id: NotRequired[str] - r"""Unique identifier for a push operation.""" + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class PushOperationRef(BaseModel): - data_type: Annotated[Optional[DataType], pydantic.Field(alias="dataType")] = None - r"""Available data types""" - id: Optional[str] = None - r"""Unique identifier for a push operation.""" +from __future__ import annotations +from codat_sync_for_expenses.models.shared.datatype 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_model(self, handler): - optional_fields = set(["dataType", "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} + """ + PushOperationRef + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Unique identifier for a push operation.") + data_type: Optional[DataType] = 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)) - 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 PushOperationRef 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: - PushOperationRef.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. + * 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[DataType]] + additional_properties: NotRequired[Dict[str, Any]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushoperations.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushoperations.py index d9b260d07..9b54b33e1 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushoperations.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushoperations.py @@ -1,58 +1,124 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations -from .links import Links, LinksTypedDict -from .pushoperation import PushOperation, PushOperationTypedDict -from codat_sync_for_expenses.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_expenses.models.shared.links import Links, LinksTypedDict +from codat_sync_for_expenses.models.shared.pushoperation import PushOperation, PushOperationTypedDict +from typing import Optional, Set +from typing_extensions import Self +class PushOperations(BaseModel): -class PushOperationsTypedDict(TypedDict): - links: LinksTypedDict - 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.""" - results: NotRequired[List[PushOperationTypedDict]] + @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=(), + ) -class PushOperations(BaseModel): - links: Annotated[Links, pydantic.Field(alias="_links")] - page_number: Annotated[int, pydantic.Field(alias="pageNumber")] - r"""Current page number.""" + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - page_size: Annotated[int, pydantic.Field(alias="pageSize")] - r"""Number of items to return in results array.""" + 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()) - total_results: Annotated[int, pydantic.Field(alias="totalResults")] - r"""Total number of items.""" + @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)) - results: Optional[List[PushOperation]] = 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 PushOperations 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": [PushOperation.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None + }) + return _obj -try: - PushOperations.model_rebuild() -except NameError: - pass + + + + +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-expenses/src/codat_sync_for_expenses/models/shared/pushoperationstatus.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushoperationstatus.py index 09fa8b1f2..1db74482f 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushoperationstatus.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushoperationstatus.py @@ -1,13 +1,39 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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): - r"""The current status of the push operation.""" + """ + 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)) + - PENDING = "Pending" - FAILED = "Failed" - SUCCESS = "Success" - TIMED_OUT = "TimedOut" diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushoption.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushoption.py index 60dd67265..1a76c1ce0 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushoption.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushoption.py @@ -1,83 +1,149 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .pushoptionchoice import PushOptionChoice, PushOptionChoiceTypedDict -from .pushoptionproperty import PushOptionProperty, PushOptionPropertyTypedDict -from .pushoptiontype import PushOptionType -from .pushvalidationinfo import PushValidationInfo, PushValidationInfoTypedDict -from codat_sync_for_expenses.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 - - -class PushOptionTypedDict(TypedDict): - display_name: str - r"""The property's display name.""" - required: bool - r"""The property is required if `True`.""" - type: PushOptionType - r"""The option type.""" - description: NotRequired[str] - r"""A description of the property.""" - options: NotRequired[Nullable[List[PushOptionChoiceTypedDict]]] - properties: NotRequired[Nullable[Dict[str, PushOptionPropertyTypedDict]]] - validation: NotRequired[PushValidationInfoTypedDict] +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class PushOption(BaseModel): - display_name: Annotated[str, pydantic.Field(alias="displayName")] - r"""The property's display name.""" - - required: bool - r"""The property is required if `True`.""" - - type: PushOptionType - r"""The option type.""" + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - description: Optional[str] = None - r"""A description of the property.""" + Do not edit the class manually. +""" # noqa: E501 - options: OptionalNullable[List[PushOptionChoice]] = UNSET - properties: OptionalNullable[Dict[str, PushOptionProperty]] = UNSET +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - validation: Optional[PushValidationInfo] = None +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_expenses.models.shared.pushoptionchoice import PushOptionChoice, PushOptionChoiceTypedDict +from codat_sync_for_expenses.models.shared.pushoptionproperty import PushOptionProperty, PushOptionPropertyTypedDict +from codat_sync_for_expenses.models.shared.pushoptiontype import PushOptionType +from codat_sync_for_expenses.models.shared.pushvalidationinfo import PushValidationInfo, PushValidationInfoTypedDict +from typing import Optional, Set +from typing_extensions import Self + +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL +class PushOption(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["description", "options", "properties", "validation"]) - nullable_fields = set(["options", "properties"]) + 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 + _nullable = {'options', 'properties'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + PushOption + """ # noqa: E501 + type: PushOptionType + display_name: str = Field(description="The property's display name.", alias="displayName") + description: Optional[str] = Field(default=None, description="A description of the property.") + required: bool = Field(description="The property is required if `True`.") + properties: OptionalNullable[Dict[str, PushOptionProperty]] = UNSET + options: OptionalNullable[List[PushOptionChoice]] = UNSET + validation: Optional[PushValidationInfo] = None + __properties: ClassVar[List[str]] = ["type", "displayName", "description", "required", "properties", "options", "validation"] + + 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 PushOption 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 value in properties (dict) + _field_dict = {} + if self.properties: + for _key_properties in self.properties: + if self.properties[_key_properties]: + _field_dict[_key_properties] = self.properties[_key_properties].to_dict() + _dict['properties'] = _field_dict + # override the default output from pydantic by calling `to_dict()` of each item in options (list) + _items = [] + if self.options: + for _item_options in self.options: + if _item_options: + _items.append(_item_options.to_dict()) + _dict['options'] = _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 PushOption 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"), + "displayName": obj.get("displayName"), + "description": obj.get("description"), + "required": obj.get("required"), + "properties": dict( + (_k, PushOptionProperty.from_dict(_v)) + for _k, _v in obj["properties"].items() ) + if obj.get("properties") is not None + else None, + "options": [PushOptionChoice.from_dict(_item) for _item in obj["options"]] if obj.get("options") is not None else None, + "validation": PushValidationInfo.from_dict(obj["validation"]) if obj.get("validation") is not None else None + }) + return _obj + - 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: - PushOption.model_rebuild() -except NameError: - pass +class PushOptionTypedDict(TypedDict): + """TypedDict variant of PushOption, for dict-literal request/response inputs.""" + type: PushOptionType + display_name: NotRequired[str] + description: NotRequired[Optional[str]] + required: NotRequired[bool] + properties: NotRequired[Optional[Dict[str, PushOptionPropertyTypedDict]]] + options: NotRequired[Optional[List[PushOptionChoiceTypedDict]]] + validation: NotRequired[Optional[PushValidationInfoTypedDict]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushoptionchoice.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushoptionchoice.py index 34c6e6093..a655a1d0c 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushoptionchoice.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushoptionchoice.py @@ -1,63 +1,113 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations -from .pushoptiontype import PushOptionType -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import 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_expenses.models.shared.pushoptiontype import PushOptionType +from typing import Optional, Set +from typing_extensions import Self +class PushOptionChoice(BaseModel): -class PushOptionChoiceTypedDict(TypedDict): - description: NotRequired[str] - r"""A description of the property.""" - display_name: NotRequired[str] - r"""The property's display name.""" - required: NotRequired[bool] - r"""The property is required if `True`.""" - type: NotRequired[PushOptionType] - r"""The option type.""" - value: NotRequired[str] - r"""Allowed value for field.""" + @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} + """ + PushOptionChoice + """ # noqa: E501 + value: Optional[str] = Field(default=None, description="Allowed value for field.") + type: Optional[PushOptionType] = None + display_name: Optional[str] = Field(default=None, description="The property's display name.", alias="displayName") + description: Optional[str] = Field(default=None, description="A description of the property.") + required: Optional[bool] = Field(default=None, description="The property is required if `True`.") + __properties: ClassVar[List[str]] = ["value", "type", "displayName", "description", "required"] + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) -class PushOptionChoice(BaseModel): - description: Optional[str] = None - r"""A description of the property.""" - display_name: Annotated[Optional[str], pydantic.Field(alias="displayName")] = None - r"""The property's display name.""" + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - required: Optional[bool] = None - r"""The property is required if `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()) - type: Optional[PushOptionType] = None - r"""The option type.""" + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of PushOptionChoice from a JSON string""" + return cls.from_dict(json.loads(json_str)) - value: Optional[str] = None - r"""Allowed value for field.""" + 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( - ["description", "displayName", "required", "type", "value"] + 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, ) - serialized = handler(self) - m = {} + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of PushOptionChoice from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + _obj = cls.model_validate({ + "value": obj.get("value"), + "type": obj.get("type"), + "displayName": obj.get("displayName"), + "description": obj.get("description"), + "required": obj.get("required") + }) + return _obj - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - return m -try: - PushOptionChoice.model_rebuild() -except NameError: - pass + +class PushOptionChoiceTypedDict(TypedDict): + """TypedDict variant of PushOptionChoice, for dict-literal request/response inputs.""" + value: NotRequired[Optional[str]] + type: NotRequired[Optional[PushOptionType]] + display_name: NotRequired[Optional[str]] + description: NotRequired[Optional[str]] + required: NotRequired[Optional[bool]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushoptionproperty.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushoptionproperty.py index 6d955c8ea..191141c08 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushoptionproperty.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushoptionproperty.py @@ -1,82 +1,150 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from __future__ import annotations -from .pushoptionchoice import PushOptionChoice, PushOptionChoiceTypedDict -from .pushoptiontype import PushOptionType -from .pushvalidationinfo import PushValidationInfo, PushValidationInfoTypedDict -from codat_sync_for_expenses.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 +# coding: utf-8 +""" + Expenses -class PushOptionPropertyTypedDict(TypedDict): - description: str - r"""A description of the property.""" - display_name: str - r"""The property's display name.""" - required: bool - r"""The property is required if `True`.""" - type: PushOptionType - r"""The option type.""" - options: NotRequired[Nullable[List[PushOptionChoiceTypedDict]]] - properties: NotRequired[Nullable[Dict[str, PushOptionPropertyTypedDict]]] - validation: NotRequired[PushValidationInfoTypedDict] + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) -class PushOptionProperty(BaseModel): - description: str - r"""A description of the property.""" + Do not edit the class manually. +""" # noqa: E501 - display_name: Annotated[str, pydantic.Field(alias="displayName")] - r"""The property's display name.""" - required: bool - r"""The property is required if `True`.""" - - type: PushOptionType - r"""The option type.""" - - options: OptionalNullable[List[PushOptionChoice]] = UNSET +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - properties: OptionalNullable[Dict[str, PushOptionProperty]] = UNSET +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_expenses.models.shared.pushoptionchoice import PushOptionChoice, PushOptionChoiceTypedDict +from codat_sync_for_expenses.models.shared.pushoptiontype import PushOptionType +from codat_sync_for_expenses.models.shared.pushvalidationinfo import PushValidationInfo, PushValidationInfoTypedDict +from typing import Optional, Set +from typing_extensions import Self - validation: Optional[PushValidationInfo] = None +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL +class PushOptionProperty(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["options", "properties", "validation"]) - nullable_fields = set(["options", "properties"]) + 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 + _nullable = {'options', 'properties'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + PushOptionProperty + """ # noqa: E501 + type: PushOptionType + display_name: str = Field(description="The property's display name.", alias="displayName") + description: str = Field(description="A description of the property.") + required: bool = Field(description="The property is required if `True`.") + properties: OptionalNullable[Dict[str, PushOptionProperty]] = UNSET + options: OptionalNullable[List[PushOptionChoice]] = UNSET + validation: Optional[PushValidationInfo] = None + __properties: ClassVar[List[str]] = ["type", "displayName", "description", "required", "properties", "options", "validation"] + + 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 PushOptionProperty 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 value in properties (dict) + _field_dict = {} + if self.properties: + for _key_properties in self.properties: + if self.properties[_key_properties]: + _field_dict[_key_properties] = self.properties[_key_properties].to_dict() + _dict['properties'] = _field_dict + # override the default output from pydantic by calling `to_dict()` of each item in options (list) + _items = [] + if self.options: + for _item_options in self.options: + if _item_options: + _items.append(_item_options.to_dict()) + _dict['options'] = _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 PushOptionProperty 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"), + "displayName": obj.get("displayName"), + "description": obj.get("description"), + "required": obj.get("required"), + "properties": dict( + (_k, PushOptionProperty.from_dict(_v)) + for _k, _v in obj["properties"].items() ) + if obj.get("properties") is not None + else None, + "options": [PushOptionChoice.from_dict(_item) for _item in obj["options"]] if obj.get("options") is not None else None, + "validation": PushValidationInfo.from_dict(obj["validation"]) if obj.get("validation") is not None else None + }) + return _obj + +# TODO: Rewrite to not use raise_errors +PushOptionProperty.model_rebuild(raise_errors=False) - 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: - PushOptionProperty.model_rebuild() -except NameError: - pass +class PushOptionPropertyTypedDict(TypedDict): + """TypedDict variant of PushOptionProperty, for dict-literal request/response inputs.""" + type: PushOptionType + display_name: NotRequired[str] + description: NotRequired[str] + required: NotRequired[bool] + properties: NotRequired[Optional[Dict[str, PushOptionPropertyTypedDict]]] + options: NotRequired[Optional[List[PushOptionChoiceTypedDict]]] + validation: NotRequired[Optional[PushValidationInfoTypedDict]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushoptiontype.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushoptiontype.py index c9c246f2a..513212fb3 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushoptiontype.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushoptiontype.py @@ -1,17 +1,43 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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 PushOptionType(str, Enum): - r"""The option type.""" - - ARRAY = "Array" - OBJECT = "Object" - STRING = "String" - NUMBER = "Number" - BOOLEAN = "Boolean" - DATE_TIME = "DateTime" - FILE = "File" - MULTI_PART = "MultiPart" + """ + The option type. + """ + + """ + allowed enum values + """ + ARRAY = 'Array' + OBJECT = 'Object' + STRING = 'String' + NUMBER = 'Number' + BOOLEAN = 'Boolean' + DATE_TIME = 'DateTime' + FILE = 'File' + MULTI_PART = 'MultiPart' + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of PushOptionType from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushvalidationinfo.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushvalidationinfo.py index 407a0a1ea..eba97114f 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushvalidationinfo.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/pushvalidationinfo.py @@ -1,50 +1,136 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .pushfieldvalidation import PushFieldValidation, PushFieldValidationTypedDict -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from pydantic import model_serializer -from typing import List -from typing_extensions import NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class PushValidationInfoTypedDict(TypedDict): - information: NotRequired[Nullable[List[PushFieldValidationTypedDict]]] - warnings: NotRequired[Nullable[List[PushFieldValidationTypedDict]]] + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class PushValidationInfo(BaseModel): - information: OptionalNullable[List[PushFieldValidation]] = UNSET - warnings: OptionalNullable[List[PushFieldValidation]] = UNSET +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_expenses.models.shared.pushfieldvalidation import PushFieldValidation, PushFieldValidationTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL +class PushValidationInfo(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["information", "warnings"]) - nullable_fields = set(["information", "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 = {'information', 'warnings'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + PushValidationInfo + """ # noqa: E501 + warnings: OptionalNullable[List[PushFieldValidation]] = UNSET + information: OptionalNullable[List[PushFieldValidation]] = UNSET + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["warnings", "information"] + + 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 PushValidationInfo 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 warnings (list) + _items = [] + if self.warnings: + for _item_warnings in self.warnings: + if _item_warnings: + _items.append(_item_warnings.to_dict()) + _dict['warnings'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in information (list) + _items = [] + if self.information: + for _item_information in self.information: + if _item_information: + _items.append(_item_information.to_dict()) + _dict['information'] = _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 PushValidationInfo from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "warnings": [PushFieldValidation.from_dict(_item) for _item in obj["warnings"]] if obj.get("warnings") is not None else None, + "information": [PushFieldValidation.from_dict(_item) for _item in obj["information"]] if obj.get("information") is not None else None + }) + # 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 PushValidationInfoTypedDict(TypedDict): + """TypedDict variant of PushValidationInfo, for dict-literal request/response inputs.""" + warnings: NotRequired[Optional[List[PushFieldValidationTypedDict]]] + information: NotRequired[Optional[List[PushFieldValidationTypedDict]]] + additional_properties: NotRequired[Dict[str, Any]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/recordref.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/recordref.py index 93485c345..3390d0591 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/recordref.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/recordref.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_expenses.types import BaseModel, UNSET_SENTINEL -from pydantic import model_serializer -from typing import Optional -from typing_extensions import NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class RecordRefTypedDict(TypedDict): - id: NotRequired[str] - r"""Identifier of linked reference from mapping options.""" + The version of the OpenAPI document: prealpha + Contact: expenses@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 RecordRef(BaseModel): - id: Optional[str] = None - r"""Identifier of linked reference from mapping options.""" @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} + """ + RecordRef + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Identifier of linked reference from mapping options.") + __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 RecordRef 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 RecordRef 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 RecordRefTypedDict(TypedDict): + """TypedDict variant of RecordRef, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/reimbursableexpensetransaction.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/reimbursableexpensetransaction.py index 0826b5048..923b54a90 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/reimbursableexpensetransaction.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/reimbursableexpensetransaction.py @@ -1,260 +1,150 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from __future__ import annotations -from .apaccountref import ApAccountRef, ApAccountRefTypedDict -from .reimbursableexpensetransactionline import ( - ReimbursableExpenseTransactionLine, - ReimbursableExpenseTransactionLineTypedDict, -) -from .reimbursementcontactref import ( - ReimbursementContactRef, - ReimbursementContactRefTypedDict, -) -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from codat_sync_for_expenses.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 ReimbursableExpenseTransactionTypedDict(TypedDict): - contact_ref: ReimbursementContactRefTypedDict - currency: str - r"""Currency the transaction was recorded in.""" - due_date: 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 - ``` - +# coding: utf-8 +""" + Expenses - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | - - 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. - """ - id: str - r"""Your unique identifier for the transaction.""" - issue_date: 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. - """ - ap_account_ref: NotRequired[Nullable[ApAccountRefTypedDict]] - 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. + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - Currency rates in Codat are implemented as the multiple of foreign currency units to each base currency unit. + Do not edit the class manually. +""" # noqa: E501 - 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. | - """ - lines: NotRequired[List[ReimbursableExpenseTransactionLineTypedDict]] - r"""Array of transaction lines.""" - notes: NotRequired[str] - r"""Any private, company notes about the transaction.""" - reference: NotRequired[Nullable[str]] - r"""User-friendly reference for the reimbursable expense.""" +from __future__ import annotations +from decimal import Decimal +from codat_sync_for_expenses.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 Any, ClassVar, Dict, List, Optional, Union +from typing_extensions import Annotated, NotRequired, TypedDict +from codat_sync_for_expenses.models.shared.apaccountref import ApAccountRef, ApAccountRefTypedDict +from codat_sync_for_expenses.models.shared.reimbursableexpensetransactionline import ReimbursableExpenseTransactionLine, ReimbursableExpenseTransactionLineTypedDict +from codat_sync_for_expenses.models.shared.reimbursementcontactref import ReimbursementContactRef, ReimbursementContactRefTypedDict +from typing import Optional, Set +from typing_extensions import Self +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL class ReimbursableExpenseTransaction(BaseModel): - contact_ref: Annotated[ReimbursementContactRef, pydantic.Field(alias="contactRef")] - - currency: str - r"""Currency the transaction was recorded in.""" - - due_date: Annotated[str, pydantic.Field(alias="dueDate")] - 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. - """ - - id: str - r"""Your unique identifier for the transaction.""" - - issue_date: Annotated[str, pydantic.Field(alias="issueDate")] - 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. - """ - - ap_account_ref: Annotated[ - OptionalNullable[ApAccountRef], pydantic.Field(alias="apAccountRef") - ] = UNSET - - 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 | - - - ### 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. | - """ - - lines: Optional[List[ReimbursableExpenseTransactionLine]] = None - r"""Array of transaction lines.""" - - notes: Optional[str] = None - r"""Any private, company notes about the transaction.""" - - reference: OptionalNullable[str] = UNSET - r"""User-friendly reference for the reimbursable expense.""" @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - ["apAccountRef", "currencyRate", "lines", "notes", "reference"] - ) - nullable_fields = set(["apAccountRef", "currencyRate", "reference"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + _nullable = {'apAccountRef', 'ap_account_ref', '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) + } + """ + ReimbursableExpenseTransaction + """ # noqa: E501 + id: str = Field(description="Your unique identifier for the transaction.") + reference: OptionalNullable[str] = Field(default=UNSET, description="User-friendly reference for the reimbursable expense.") + contact_ref: ReimbursementContactRef = Field(alias="contactRef") + ap_account_ref: OptionalNullable[ApAccountRef] = Field(default=UNSET, alias="apAccountRef") + issue_date: str = Field(description="Date of the transaction was recorded.", alias="issueDate") + due_date: str = Field(description="Date the supplier is due to be paid.", alias="dueDate") + currency: str = Field(description="Currency the transaction was recorded in.") + 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") + notes: Optional[str] = Field(default=None, description="Any private, company notes about the transaction.") + lines: Optional[List[ReimbursableExpenseTransactionLine]] = Field(default=None, description="Array of transaction lines.") + __properties: ClassVar[List[str]] = ["id", "reference", "contactRef", "apAccountRef", "issueDate", "dueDate", "currency", "currencyRate", "notes", "lines"] + + 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 ReimbursableExpenseTransaction 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 contact_ref + if self.contact_ref: + _dict['contactRef'] = self.contact_ref.to_dict() + # override the default output from pydantic by calling `to_dict()` of ap_account_ref + if self.ap_account_ref: + _dict['apAccountRef'] = self.ap_account_ref.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in lines (list) + _items = [] + if self.lines: + for _item_lines in self.lines: + if _item_lines: + _items.append(_item_lines.to_dict()) + _dict['lines'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ReimbursableExpenseTransaction 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"), + "contactRef": ReimbursementContactRef.from_dict(obj["contactRef"]) if obj.get("contactRef") is not None else None, + "apAccountRef": ApAccountRef.from_dict(obj["apAccountRef"]) if obj.get("apAccountRef") is not None else None, + "issueDate": obj.get("issueDate"), + "dueDate": obj.get("dueDate"), + "currency": obj.get("currency"), + "currencyRate": obj.get("currencyRate"), + "notes": obj.get("notes"), + "lines": [ReimbursableExpenseTransactionLine.from_dict(_item) for _item in obj["lines"]] if obj.get("lines") is not None else None + }) + return _obj - 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: - ReimbursableExpenseTransaction.model_rebuild() -except NameError: - pass +class ReimbursableExpenseTransactionTypedDict(TypedDict): + """TypedDict variant of ReimbursableExpenseTransaction, for dict-literal request/response inputs.""" + id: NotRequired[str] + reference: NotRequired[Optional[str]] + contact_ref: NotRequired[ReimbursementContactRefTypedDict] + ap_account_ref: NotRequired[Optional[ApAccountRefTypedDict]] + issue_date: NotRequired[str] + due_date: NotRequired[str] + currency: NotRequired[str] + currency_rate: NotRequired[Optional[Decimal]] + notes: NotRequired[Optional[str]] + lines: NotRequired[Optional[List[ReimbursableExpenseTransactionLineTypedDict]]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/reimbursableexpensetransactionline.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/reimbursableexpensetransactionline.py index 177ffe76a..2cfbbbf96 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/reimbursableexpensetransactionline.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/reimbursableexpensetransactionline.py @@ -1,124 +1,151 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .invoiceto import InvoiceTo, InvoiceToTypedDict -from .itemref import ItemRef, ItemRefTypedDict -from .recordref import RecordRef, RecordRefTypedDict -from .trackingref import TrackingRef, TrackingRefTypedDict -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from codat_sync_for_expenses.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 +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 -class ReimbursableExpenseTransactionLineTypedDict(TypedDict): - net_amount: Decimal - r"""Amount of the line, exclusive of tax.""" - account_ref: NotRequired[RecordRefTypedDict] - description: NotRequired[str] - r"""line description""" - invoice_to: NotRequired[Nullable[InvoiceToTypedDict]] - r"""Unique identifier for the customer billed for the transaction. The `invoiceTo` object is currently supported only for QuickBooks Online and QuickBooks Desktop.""" - item_ref: NotRequired[Nullable[ItemRefTypedDict]] - tax_amount: NotRequired[Decimal] - r"""Amount of tax for the line.""" - tax_rate_ref: NotRequired[RecordRefTypedDict] - tracking_refs: NotRequired[Nullable[List[TrackingRefTypedDict]]] +from __future__ import annotations +from decimal import Decimal +from codat_sync_for_expenses.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 Any, ClassVar, Dict, List, Optional, Union +from typing_extensions import Annotated, NotRequired, TypedDict +from codat_sync_for_expenses.models.shared.invoiceto import InvoiceTo, InvoiceToTypedDict +from codat_sync_for_expenses.models.shared.itemref import ItemRef, ItemRefTypedDict +from codat_sync_for_expenses.models.shared.recordref import RecordRef, RecordRefTypedDict +from codat_sync_for_expenses.models.shared.trackingref import TrackingRef, TrackingRefTypedDict +from typing import Optional, Set +from typing_extensions import Self + +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL class ReimbursableExpenseTransactionLine(BaseModel): - net_amount: Annotated[ - Annotated[ - Decimal, - BeforeValidator(validate_decimal), - PlainSerializer(serialize_decimal(False)), - ], - pydantic.Field(alias="netAmount"), - ] - r"""Amount of the line, exclusive of tax.""" - - account_ref: Annotated[Optional[RecordRef], pydantic.Field(alias="accountRef")] = ( - None + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'invoiceTo', 'invoice_to', 'itemRef', 'item_ref', '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) + } + """ + ReimbursableExpenseTransactionLine + """ # noqa: E501 + description: Optional[str] = Field(default=None, description="line description") + net_amount: Annotated[Decimal, BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(description="Amount of the line, exclusive of tax.", alias="netAmount") + tax_amount: Annotated[Optional[Decimal], BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(default=None, description="Amount of tax for the line.", alias="taxAmount") + tax_rate_ref: Optional[RecordRef] = Field(default=None, alias="taxRateRef") + account_ref: Optional[RecordRef] = Field(default=None, description="The `accountRef` contains the `id` of the account the transaction is against. The `accountRef` object is required for all integrations except QBD which currently supports either itemRef or accountRef.", alias="accountRef") + item_ref: OptionalNullable[ItemRef] = Field(default=UNSET, alias="itemRef") + tracking_refs: OptionalNullable[List[TrackingRef]] = Field(default=UNSET, alias="trackingRefs") + invoice_to: OptionalNullable[InvoiceTo] = Field(default=UNSET, alias="invoiceTo") + __properties: ClassVar[List[str]] = ["description", "netAmount", "taxAmount", "taxRateRef", "accountRef", "itemRef", "trackingRefs", "invoiceTo"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), ) - description: Optional[str] = None - r"""line description""" - invoice_to: Annotated[ - OptionalNullable[InvoiceTo], pydantic.Field(alias="invoiceTo") - ] = UNSET - r"""Unique identifier for the customer billed for the transaction. The `invoiceTo` object is currently supported only for QuickBooks Online and QuickBooks Desktop.""" + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - item_ref: Annotated[OptionalNullable[ItemRef], pydantic.Field(alias="itemRef")] = ( - UNSET - ) + 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()) - tax_amount: Annotated[ - Annotated[ - Optional[Decimal], - BeforeValidator(validate_decimal), - PlainSerializer(serialize_decimal(False)), - ], - pydantic.Field(alias="taxAmount"), - ] = None - r"""Amount of tax for the line.""" - - tax_rate_ref: Annotated[Optional[RecordRef], pydantic.Field(alias="taxRateRef")] = ( - None - ) + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ReimbursableExpenseTransactionLine from a JSON string""" + return cls.from_dict(json.loads(json_str)) - tracking_refs: Annotated[ - OptionalNullable[List[TrackingRef]], pydantic.Field(alias="trackingRefs") - ] = UNSET + 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( - [ - "accountRef", - "description", - "invoiceTo", - "itemRef", - "taxAmount", - "taxRateRef", - "trackingRefs", - ] + 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, ) - nullable_fields = set(["invoiceTo", "itemRef", "trackingRefs"]) - 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: - ReimbursableExpenseTransactionLine.model_rebuild() -except NameError: - pass + # 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 account_ref + if self.account_ref: + _dict['accountRef'] = self.account_ref.to_dict() + # override the default output from pydantic by calling `to_dict()` of item_ref + if self.item_ref: + _dict['itemRef'] = self.item_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 + # override the default output from pydantic by calling `to_dict()` of invoice_to + if self.invoice_to: + _dict['invoiceTo'] = self.invoice_to.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ReimbursableExpenseTransactionLine 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"), + "netAmount": obj.get("netAmount"), + "taxAmount": obj.get("taxAmount"), + "taxRateRef": RecordRef.from_dict(obj["taxRateRef"]) if obj.get("taxRateRef") is not None else None, + "accountRef": RecordRef.from_dict(obj["accountRef"]) if obj.get("accountRef") is not None else None, + "itemRef": ItemRef.from_dict(obj["itemRef"]) if obj.get("itemRef") is not None else None, + "trackingRefs": [TrackingRef.from_dict(_item) for _item in obj["trackingRefs"]] if obj.get("trackingRefs") is not None else None, + "invoiceTo": InvoiceTo.from_dict(obj["invoiceTo"]) if obj.get("invoiceTo") is not None else None + }) + return _obj + + + + + +class ReimbursableExpenseTransactionLineTypedDict(TypedDict): + """TypedDict variant of ReimbursableExpenseTransactionLine, for dict-literal request/response inputs.""" + description: NotRequired[Optional[str]] + net_amount: NotRequired[Decimal] + tax_amount: NotRequired[Optional[Decimal]] + tax_rate_ref: NotRequired[Optional[RecordRefTypedDict]] + account_ref: NotRequired[Optional[RecordRefTypedDict]] + item_ref: NotRequired[Optional[ItemRefTypedDict]] + tracking_refs: NotRequired[Optional[List[TrackingRefTypedDict]]] + invoice_to: NotRequired[Optional[InvoiceToTypedDict]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/reimbursementcontactref.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/reimbursementcontactref.py index 51cb2d5ec..8c4e93e83 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/reimbursementcontactref.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/reimbursementcontactref.py @@ -1,15 +1,99 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel -from typing_extensions import TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class ReimbursementContactRefTypedDict(TypedDict): - id: str - r"""Identifier of contact.""" + The version of the OpenAPI document: prealpha + Contact: expenses@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 import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict class ReimbursementContactRef(BaseModel): - id: str - r"""Identifier of contact.""" + + @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} + """ + ReimbursementContactRef + """ # noqa: E501 + id: str = Field(description="Identifier of contact.") + __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 ReimbursementContactRef 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 ReimbursementContactRef 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 ReimbursementContactRefTypedDict(TypedDict): + """TypedDict variant of ReimbursementContactRef, for dict-literal request/response inputs.""" + id: NotRequired[str] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/schema_datatype.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/schema_datatype.py index aa72f531c..8609d13ac 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/schema_datatype.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/schema_datatype.py @@ -1,52 +1,6 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - from __future__ import annotations -from enum import Enum +from enum import Enum -class SchemaDataType(str, Enum): - r"""Available data types""" - 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" +from codat_sync_for_expenses.models._compat.schema_datatype import SchemaDataType diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/schema_transaction.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/schema_transaction.py index 1a9d09289..0fea75e1c 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/schema_transaction.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/schema_transaction.py @@ -1,75 +1,129 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .integrationtype import IntegrationType -from .transactionstatus import TransactionStatus -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class SchemaTransactionTypedDict(TypedDict): - integration_type: NotRequired[Nullable[IntegrationType]] - r"""Type of transaction that has been processed e.g. Expense or Bank Feed.""" - message: NotRequired[Nullable[str]] - r"""Metadata such as validation errors or the resulting record created in the accounting software.""" - status: NotRequired[Nullable[TransactionStatus]] - r"""Status of the transaction.""" - transaction_id: NotRequired[Nullable[str]] - r"""Your unique idenfier of the transaction.""" + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class SchemaTransaction(BaseModel): - integration_type: Annotated[ - OptionalNullable[IntegrationType], pydantic.Field(alias="integrationType") - ] = IntegrationType.EXPENSES - r"""Type of transaction that has been processed e.g. Expense or Bank Feed.""" - message: OptionalNullable[str] = UNSET - r"""Metadata such as validation errors or the resulting record created in the accounting software.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - status: OptionalNullable[TransactionStatus] = UNSET - r"""Status of the transaction.""" +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_sync_for_expenses.models.shared.integrationtype import IntegrationType +from codat_sync_for_expenses.models.shared.transactionstatus import TransactionStatus +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict - transaction_id: Annotated[ - OptionalNullable[str], pydantic.Field(alias="transactionId") - ] = UNSET - r"""Your unique idenfier of the transaction.""" +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL +class SchemaTransaction(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["integrationType", "message", "status", "transactionId"]) - nullable_fields = set(["integrationType", "message", "status", "transactionId"]) + 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: - SchemaTransaction.model_rebuild() -except NameError: - pass + _nullable = {'message', 'status', 'transactionId', 'transaction_id'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + SchemaTransaction + """ # noqa: E501 + transaction_id: OptionalNullable[str] = Field(default=UNSET, description="Your unique idenfier of the transaction.", alias="transactionId") + status: OptionalNullable[TransactionStatus] = UNSET + message: OptionalNullable[str] = Field(default=UNSET, description="Metadata such as validation errors or the resulting record created in the accounting software.") + integration_type: Optional[IntegrationType] = Field(default=IntegrationType.EXPENSES, alias="integrationType") + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["transactionId", "status", "message", "integrationType"] + + 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 SchemaTransaction 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 SchemaTransaction from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "transactionId": obj.get("transactionId"), + "status": obj.get("status"), + "message": obj.get("message"), + "integrationType": obj.get("integrationType") if obj.get("integrationType") is not None else IntegrationType.EXPENSES + }) + # 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 SchemaTransactionTypedDict(TypedDict): + """TypedDict variant of SchemaTransaction, for dict-literal request/response inputs.""" + transaction_id: NotRequired[Optional[str]] + status: NotRequired[Optional[TransactionStatus]] + message: NotRequired[Optional[str]] + integration_type: NotRequired[Optional[IntegrationType]] + additional_properties: NotRequired[Dict[str, Any]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/security.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/security.py index 0963a8d5f..7b1133901 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/security.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/security.py @@ -1,9 +1,12 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""Security model for codat_sync_for_expenses. + +Generated by pipeline/postprocess_generated.py — do not edit by hand. +""" from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel -from codat_sync_for_expenses.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-expenses/src/codat_sync_for_expenses/models/shared/status.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/status.py index bab5b3828..a39e393b7 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/status.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/status.py @@ -1,30 +1,56 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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): - r"""The current status of the dataset.""" - - 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" + """ + 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-expenses/src/codat_sync_for_expenses/models/shared/supplementaldata.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/supplementaldata.py index 43cc98412..f577e4a1c 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/supplementaldata.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/supplementaldata.py @@ -1,56 +1,104 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from pydantic import model_serializer -from typing import Any, Dict -from typing_extensions import NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class SupplementalDataTypedDict(TypedDict): - r"""Supplemental data is additional data you can include in our standard data types. + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. - """ + Do not edit the class manually. +""" # noqa: E501 - content: NotRequired[Nullable[Dict[str, Dict[str, Any]]]] +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 typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL class SupplementalData(BaseModel): - r"""Supplemental data is additional data you can include in our standard data types. - It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'content'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } """ - + Supplemental data is additional data you can include in our standard data types. It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. + """ # noqa: E501 content: OptionalNullable[Dict[str, Dict[str, Any]]] = UNSET + __properties: ClassVar[List[str]] = ["content"] - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["content"]) - nullable_fields = set(["content"]) - 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 + 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 SupplementalData 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 SupplementalData from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "content": obj.get("content") + }) + return _obj + + + + + +class SupplementalDataTypedDict(TypedDict): + """TypedDict variant of SupplementalData, for dict-literal request/response inputs.""" + content: NotRequired[Optional[Dict[str, Dict[str, Any]]]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/supplier.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/supplier.py index d1c9f771f..b778e9093 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/supplier.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/supplier.py @@ -1,177 +1,160 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from __future__ import annotations -from .items import Items, ItemsTypedDict -from .metadata import Metadata, MetadataTypedDict -from .supplementaldata import SupplementalData, SupplementalDataTypedDict -from .supplierstatus import SupplierStatus -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict +# coding: utf-8 +""" + Expenses -class SupplierTypedDict(TypedDict): - r"""## Overview + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | - From the **Suppliers** endpoints, you can retrieve a list of [all the suppliers for a company](https://docs.codat.io/sync-for-expenses-api#/operations/list-suppliers). Suppliers' data links to accounts payable [bills](https://docs.codat.io/sync-for-expenses-api#/schemas/Bill). - """ + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - status: SupplierStatus - r"""Status of the supplier.""" - addresses: NotRequired[Nullable[List[ItemsTypedDict]]] - r"""An array of Addresses.""" - contact_name: NotRequired[Nullable[str]] - r"""Name of the main contact for the supplier.""" - default_currency: NotRequired[Nullable[str]] - r"""Default currency the supplier's transactional data is recorded in.""" - email_address: NotRequired[Nullable[str]] - r"""Email address that the supplier may be contacted on.""" - id: NotRequired[str] - r"""Identifier for the supplier, unique to the company in the accounting software.""" - metadata: NotRequired[MetadataTypedDict] - modified_date: NotRequired[str] - phone: NotRequired[Nullable[str]] - r"""Phone number that the supplier may be contacted on.""" - registration_number: NotRequired[Nullable[str]] - r"""Company number of the supplier. In the UK, this is typically the company registration number issued by Companies House.""" - source_modified_date: NotRequired[str] - supplemental_data: NotRequired[SupplementalDataTypedDict] - r"""Supplemental data is additional data you can include in our standard data types. - - It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. - """ - supplier_name: NotRequired[Nullable[str]] - r"""Name of the supplier as recorded in the accounting system, typically the company name.""" - tax_number: NotRequired[Nullable[str]] - r"""Supplier's company tax number.""" + 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_expenses.models.shared.items import Items, ItemsTypedDict +from codat_sync_for_expenses.models.shared.metadata import Metadata, MetadataTypedDict +from codat_sync_for_expenses.models.shared.supplementaldata import SupplementalData, SupplementalDataTypedDict +from codat_sync_for_expenses.models.shared.supplierstatus import SupplierStatus +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL class Supplier(BaseModel): - r"""## Overview - From the **Suppliers** endpoints, you can retrieve a list of [all the suppliers for a company](https://docs.codat.io/sync-for-expenses-api#/operations/list-suppliers). Suppliers' data links to accounts payable [bills](https://docs.codat.io/sync-for-expenses-api#/schemas/Bill). + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'addresses', 'contactName', 'contact_name', 'defaultCurrency', 'default_currency', 'emailAddress', 'email_address', 'phone', 'registrationNumber', 'registration_number', 'supplierName', 'supplier_name', 'taxNumber', 'tax_number'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } """ - + ## Overview From the **Suppliers** endpoints, you can retrieve a list of [all the suppliers for a company](https://docs.codat.io/sync-for-expenses-api#/operations/list-suppliers). Suppliers' data links to accounts payable [bills](https://docs.codat.io/sync-for-expenses-api#/schemas/Bill). + """ # noqa: E501 + modified_date: Optional[str] = Field(default=None, description="The date when the record was last fetched from the accounting software, commerce software, or open banking provider and updated in Codat’s data cache. Use it to identify and retrieve records that have changed since your last fetch. For example, filtering `modifiedDate` to today will provide new records updated in Codat today. This date is populated for all data types except for attachments, balance sheets, company information, and profit & loss reports ([read more](https://docs.codat.io/using-the-api/modified-dates#modified-date)). In Codat's data model, dates and times are represented using the ISO 8601 standard.", alias="modifiedDate") + 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 supplier, unique to the company in the accounting software.") + supplier_name: OptionalNullable[str] = Field(default=UNSET, 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[Items]] = Field(default=UNSET, description="An array of Addresses.") + registration_number: OptionalNullable[str] = Field(default=UNSET, description="Company number of the supplier. In the UK, this is typically the company registration number issued by Companies House.", alias="registrationNumber") + tax_number: OptionalNullable[str] = Field(default=UNSET, description="Supplier's company tax number.", alias="taxNumber") status: SupplierStatus - r"""Status of the supplier.""" - - addresses: OptionalNullable[List[Items]] = UNSET - r"""An array of Addresses.""" + default_currency: OptionalNullable[str] = Field(default=UNSET, description="Default currency the supplier's transactional data is recorded in.", alias="defaultCurrency") + metadata: Optional[Metadata] = None + supplemental_data: Optional[SupplementalData] = Field(default=None, alias="supplementalData") + __properties: ClassVar[List[str]] = ["modifiedDate", "sourceModifiedDate", "id", "supplierName", "contactName", "emailAddress", "phone", "addresses", "registrationNumber", "taxNumber", "status", "defaultCurrency", "metadata", "supplementalData"] - contact_name: Annotated[ - OptionalNullable[str], pydantic.Field(alias="contactName") - ] = UNSET - r"""Name of the main contact for the supplier.""" + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) - default_currency: Annotated[ - OptionalNullable[str], pydantic.Field(alias="defaultCurrency") - ] = UNSET - r"""Default currency the supplier's transactional data is recorded in.""" - email_address: Annotated[ - OptionalNullable[str], pydantic.Field(alias="emailAddress") - ] = UNSET - r"""Email address that the supplier may be contacted on.""" + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - id: Optional[str] = None - r"""Identifier for the supplier, unique to the company in the accounting software.""" + 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()) - metadata: Optional[Metadata] = None + @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)) - modified_date: Annotated[Optional[str], pydantic.Field(alias="modifiedDate")] = None + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - phone: OptionalNullable[str] = UNSET - r"""Phone number that the supplier may be contacted on.""" + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - registration_number: Annotated[ - OptionalNullable[str], pydantic.Field(alias="registrationNumber") - ] = UNSET - r"""Company number of the supplier. In the UK, this is typically the company registration number issued by Companies House.""" + * `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([ + ]) - source_modified_date: Annotated[ - Optional[str], pydantic.Field(alias="sourceModifiedDate") - ] = None + _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 + # override the default output from pydantic by calling `to_dict()` of metadata + if self.metadata: + _dict['metadata'] = self.metadata.to_dict() + # override the default output from pydantic by calling `to_dict()` of supplemental_data + if self.supplemental_data: + _dict['supplementalData'] = self.supplemental_data.to_dict() + 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({ + "modifiedDate": obj.get("modifiedDate"), + "sourceModifiedDate": obj.get("sourceModifiedDate"), + "id": obj.get("id"), + "supplierName": obj.get("supplierName"), + "contactName": obj.get("contactName"), + "emailAddress": obj.get("emailAddress"), + "phone": obj.get("phone"), + "addresses": [Items.from_dict(_item) for _item in obj["addresses"]] if obj.get("addresses") is not None else None, + "registrationNumber": obj.get("registrationNumber"), + "taxNumber": obj.get("taxNumber"), + "status": obj.get("status"), + "defaultCurrency": obj.get("defaultCurrency"), + "metadata": Metadata.from_dict(obj["metadata"]) if obj.get("metadata") is not None else None, + "supplementalData": SupplementalData.from_dict(obj["supplementalData"]) if obj.get("supplementalData") is not None else None + }) + return _obj - supplemental_data: Annotated[ - Optional[SupplementalData], pydantic.Field(alias="supplementalData") - ] = None - r"""Supplemental data is additional data you can include in our standard data types. - It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. - """ - supplier_name: Annotated[ - OptionalNullable[str], pydantic.Field(alias="supplierName") - ] = UNSET - r"""Name of the supplier as recorded in the accounting system, typically the company name.""" - tax_number: Annotated[OptionalNullable[str], pydantic.Field(alias="taxNumber")] = ( - UNSET - ) - r"""Supplier's company tax number.""" - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "addresses", - "contactName", - "defaultCurrency", - "emailAddress", - "id", - "metadata", - "modifiedDate", - "phone", - "registrationNumber", - "sourceModifiedDate", - "supplementalData", - "supplierName", - "taxNumber", - ] - ) - nullable_fields = set( - [ - "addresses", - "contactName", - "defaultCurrency", - "emailAddress", - "phone", - "registrationNumber", - "supplierName", - "taxNumber", - ] - ) - 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.""" + modified_date: NotRequired[Optional[str]] + source_modified_date: NotRequired[Optional[str]] + 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[ItemsTypedDict]]] + registration_number: NotRequired[Optional[str]] + tax_number: NotRequired[Optional[str]] + status: SupplierStatus + default_currency: NotRequired[Optional[str]] + metadata: NotRequired[Optional[MetadataTypedDict]] + supplemental_data: NotRequired[Optional[SupplementalDataTypedDict]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/supplierdetails.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/supplierdetails.py index 3fdf7999f..609eb579e 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/supplierdetails.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/supplierdetails.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_expenses.types import BaseModel, UNSET_SENTINEL -from pydantic import model_serializer -from typing import Optional -from typing_extensions import NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class SupplierDetailsTypedDict(TypedDict): - id: NotRequired[str] - r"""Identifier for the supplier, unique to the company in the accounting software.""" + The version of the OpenAPI document: prealpha + Contact: expenses@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 SupplierDetails(BaseModel): - id: Optional[str] = None - r"""Identifier for the supplier, unique to the company in the accounting software.""" @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} + """ + SupplierDetails + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Identifier for the customer, unique to the company 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 SupplierDetails 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 SupplierDetails 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 SupplierDetailsTypedDict(TypedDict): + """TypedDict variant of SupplierDetails, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/suppliers.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/suppliers.py index 8f79af1f0..d9596d474 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/suppliers.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/suppliers.py @@ -1,58 +1,125 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations -from .links import Links, LinksTypedDict -from .supplier import Supplier, SupplierTypedDict -from codat_sync_for_expenses.types import BaseModel, Nullable, 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_expenses.models.shared.links import Links, LinksTypedDict +from codat_sync_for_expenses.models.shared.supplier import Supplier, SupplierTypedDict +from typing import Optional, Set +from typing_extensions import Self +from codat_sync_for_expenses.types import Nullable +class Suppliers(BaseModel): -class SuppliersTypedDict(TypedDict): - links: LinksTypedDict - 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.""" - results: NotRequired[List[Nullable[SupplierTypedDict]]] + @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} + """ + Suppliers + """ # 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[Nullable[Supplier]]] = None + __properties: ClassVar[List[str]] = ["pageNumber", "pageSize", "totalResults", "_links", "results"] + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) -class Suppliers(BaseModel): - links: Annotated[Links, pydantic.Field(alias="_links")] - page_number: Annotated[int, pydantic.Field(alias="pageNumber")] - r"""Current page number.""" + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - page_size: Annotated[int, pydantic.Field(alias="pageSize")] - r"""Number of items to return in results array.""" + 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()) - total_results: Annotated[int, pydantic.Field(alias="totalResults")] - r"""Total number of items.""" + @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)) - results: Optional[List[Nullable[Supplier]]] = 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 Suppliers 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": [Supplier.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None + }) + return _obj -try: - Suppliers.model_rebuild() -except NameError: - pass + + + + +class SuppliersTypedDict(TypedDict): + """TypedDict variant of Suppliers, 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[Nullable[SupplierTypedDict]]]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/supplierstatus.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/supplierstatus.py index 0f7785837..9e6c8a69e 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/supplierstatus.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/supplierstatus.py @@ -1,12 +1,39 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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-expenses/src/codat_sync_for_expenses/models/shared/taxratemappinginfo.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/taxratemappinginfo.py index e739e8dbd..3170421c7 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/taxratemappinginfo.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/taxratemappinginfo.py @@ -1,111 +1,147 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .validtransactiontypes import ValidTransactionTypes -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from codat_sync_for_expenses.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 +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class TaxRateMappingInfoTypedDict(TypedDict): - code: NotRequired[Nullable[str]] - r"""Code for the tax rate from the accounting software.""" - effective_tax_rate: NotRequired[Decimal] - r"""Effective tax rate.""" - id: NotRequired[str] - r"""Unique identifier of tax rate.""" - name: NotRequired[str] - r"""Name of the tax rate in the accounting software.""" - total_tax_rate: NotRequired[Decimal] - r"""Total (not compounded) sum of the components of a tax rate.""" - valid_transaction_types: NotRequired[List[ValidTransactionTypes]] - r"""Supported transaction types for the account.""" + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.utils.serializers import serialize_decimal, validate_decimal +from codat_sync_for_expenses.models.shared.validtransactiontypes import ValidTransactionTypes +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_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL class TaxRateMappingInfo(BaseModel): - code: OptionalNullable[str] = UNSET - r"""Code for the tax rate from the accounting software.""" - - effective_tax_rate: Annotated[ - Annotated[ - Optional[Decimal], - BeforeValidator(validate_decimal), - PlainSerializer(serialize_decimal(False)), - ], - pydantic.Field(alias="effectiveTaxRate"), - ] = None - r"""Effective tax rate.""" - - id: Optional[str] = None - r"""Unique identifier of tax rate.""" - - name: Optional[str] = None - r"""Name of the tax rate in the accounting software.""" - - total_tax_rate: Annotated[ - Annotated[ - Optional[Decimal], - BeforeValidator(validate_decimal), - PlainSerializer(serialize_decimal(False)), - ], - pydantic.Field(alias="totalTaxRate"), - ] = None - r"""Total (not compounded) sum of the components of a tax rate.""" - - valid_transaction_types: Annotated[ - Optional[List[ValidTransactionTypes]], - pydantic.Field(alias="validTransactionTypes"), - ] = None - r"""Supported transaction types for the account.""" @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "code", - "effectiveTaxRate", - "id", - "name", - "totalTaxRate", - "validTransactionTypes", - ] - ) - nullable_fields = set(["code"]) + 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: - TaxRateMappingInfo.model_rebuild() -except NameError: - pass + _nullable = {'code'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + TaxRateMappingInfo + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Unique identifier of tax rate.") + name: Optional[str] = Field(default=None, description="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[Optional[Decimal], BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(default=None, description="Effective tax rate.", alias="effectiveTaxRate") + total_tax_rate: Annotated[Optional[Decimal], BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(default=None, description="Total (not compounded) sum of the components of a tax rate.", alias="totalTaxRate") + valid_transaction_types: Optional[List[ValidTransactionTypes]] = Field(default=None, description="Supported transaction types for the account.", alias="validTransactionTypes") + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["id", "name", "code", "effectiveTaxRate", "totalTaxRate", "validTransactionTypes"] + + @field_validator('valid_transaction_types') + def valid_transaction_types_validate_enum(cls, value): + """Validates the enum""" + if value is None: + return value + + for i in value: + if i not in set(['Payment', 'Refund', 'Reward', 'Chargeback']): + raise ValueError("each list item must be one of ('Payment', 'Refund', 'Reward', 'Chargeback')") + 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 TaxRateMappingInfo 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 TaxRateMappingInfo 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"), + "validTransactionTypes": obj.get("validTransactionTypes") + }) + # 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 TaxRateMappingInfoTypedDict(TypedDict): + """TypedDict variant of TaxRateMappingInfo, 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]] + valid_transaction_types: NotRequired[Optional[List[ValidTransactionTypes]]] + additional_properties: NotRequired[Dict[str, Any]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/trackingcategorymappinginfo.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/trackingcategorymappinginfo.py index 9284f0204..c9259fb94 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/trackingcategorymappinginfo.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/trackingcategorymappinginfo.py @@ -1,72 +1,127 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_expenses.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 +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class TrackingCategoryMappingInfoTypedDict(TypedDict): - has_children: NotRequired[bool] - r"""Boolean of whether the tracking category has child categories.""" - id: NotRequired[str] - r"""Unique identifier of the tracking category.""" - name: NotRequired[str] - r"""Name of the tracking category as it appears in the accounting software.""" - parent_id: NotRequired[Nullable[str]] - r"""ID of the parent tracking category""" + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class TrackingCategoryMappingInfo(BaseModel): - has_children: Annotated[Optional[bool], pydantic.Field(alias="hasChildren")] = None - r"""Boolean of whether the tracking category has child categories.""" - id: Optional[str] = None - r"""Unique identifier of the tracking category.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - name: Optional[str] = None - r"""Name of the tracking category as it appears in the accounting software.""" +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 - parent_id: Annotated[OptionalNullable[str], pydantic.Field(alias="parentId")] = ( - UNSET - ) - r"""ID of the parent tracking category""" +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL +class TrackingCategoryMappingInfo(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["hasChildren", "id", "name", "parentId"]) - nullable_fields = set(["parentId"]) + 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: - TrackingCategoryMappingInfo.model_rebuild() -except NameError: - pass + _nullable = {'parentId', 'parent_id'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + TrackingCategoryMappingInfo + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Unique identifier of the tracking category.") + name: Optional[str] = Field(default=None, description="Name of the tracking category as it appears in the accounting software.") + has_children: Optional[bool] = Field(default=None, description="Boolean of whether the tracking category has child categories.", alias="hasChildren") + parent_id: OptionalNullable[str] = Field(default=UNSET, description="ID of the parent tracking category", alias="parentId") + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["id", "name", "hasChildren", "parentId"] + + 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 TrackingCategoryMappingInfo 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 TrackingCategoryMappingInfo 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"), + "hasChildren": obj.get("hasChildren"), + "parentId": obj.get("parentId") + }) + # 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 TrackingCategoryMappingInfoTypedDict(TypedDict): + """TypedDict variant of TrackingCategoryMappingInfo, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + name: NotRequired[Optional[str]] + has_children: NotRequired[Optional[bool]] + parent_id: NotRequired[Optional[str]] + additional_properties: NotRequired[Dict[str, Any]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/trackingref.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/trackingref.py index 7a80228da..e26896ffa 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/trackingref.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/trackingref.py @@ -1,55 +1,113 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_expenses.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 +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class TrackingRefDataType(str, Enum): - r"""The type of the linked reference""" + The version of the OpenAPI document: prealpha + Contact: expenses@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): - data_type: NotRequired[TrackingRefDataType] - r"""The type of the linked reference""" - id: NotRequired[str] - r"""Unique identifier of the linked reference from mapping options or the unique identifier of the linked customer.""" +from __future__ import annotations +from codat_sync_for_expenses.models.tracking_ref_data_type import TrackingRefDataType +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 TrackingRef(BaseModel): - data_type: Annotated[ - Optional[TrackingRefDataType], pydantic.Field(alias="dataType") - ] = TrackingRefDataType.TRACKING_CATEGORIES - r"""The type of the linked reference""" - - id: Optional[str] = None - r"""Unique identifier of the linked reference from mapping options or the unique identifier of the linked customer.""" @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["dataType", "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} + """ + TrackingRef + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Unique identifier of the linked reference from mapping options or the unique identifier of the linked customer.") + data_type: Optional[TrackingRefDataType] = Field(default='trackingCategories', description="The type of the linked reference", alias="dataType") + __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(['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()) - 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 TrackingRef 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: - TrackingRef.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 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") if obj.get("dataType") is not None else 'trackingCategories' + }) + return _obj + + + + + +class TrackingRefTypedDict(TypedDict): + """TypedDict variant of TrackingRef, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + data_type: NotRequired[Optional[TrackingRefDataType]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/trackingrefadjustmenttransaction.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/trackingrefadjustmenttransaction.py index 605645b85..098088b3a 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/trackingrefadjustmenttransaction.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/trackingrefadjustmenttransaction.py @@ -1,57 +1,113 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_expenses.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 +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class TrackingRefAdjustmentTransactionDataType(str, Enum): - r"""The type of the linked reference""" + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - TRACKING_CATEGORIES = "trackingCategories" - CUSTOMERS = "customers" - SUPPLIERS = "suppliers" + Do not edit the class manually. +""" # noqa: E501 -class TrackingRefAdjustmentTransactionTypedDict(TypedDict): - data_type: NotRequired[TrackingRefAdjustmentTransactionDataType] - r"""The type of the linked reference""" - id: NotRequired[str] - r"""Unique identifier of the linked reference from mapping options or the unique identifier of the linked customer or supplier.""" +from __future__ import annotations +from codat_sync_for_expenses.models.tracking_ref_adjustment_transaction_data_type import TrackingRefAdjustmentTransactionDataType +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 TrackingRefAdjustmentTransaction(BaseModel): - data_type: Annotated[ - Optional[TrackingRefAdjustmentTransactionDataType], - pydantic.Field(alias="dataType"), - ] = TrackingRefAdjustmentTransactionDataType.TRACKING_CATEGORIES - r"""The type of the linked reference""" - - id: Optional[str] = None - r"""Unique identifier of the linked reference from mapping options or the unique identifier of the linked customer or supplier.""" @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["dataType", "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} + """ + TrackingRefAdjustmentTransaction + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Unique identifier of the linked reference from mapping options or the unique identifier of the linked customer or supplier.") + data_type: Optional[TrackingRefAdjustmentTransactionDataType] = Field(default='trackingCategories', description="The type of the linked reference", alias="dataType") + __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(['trackingCategories', 'customers', 'suppliers']): + raise ValueError("must be one of enum values ('trackingCategories', 'customers', 'suppliers')") + 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 TrackingRefAdjustmentTransaction 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: - TrackingRefAdjustmentTransaction.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 TrackingRefAdjustmentTransaction 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") if obj.get("dataType") is not None else 'trackingCategories' + }) + return _obj + + + + + +class TrackingRefAdjustmentTransactionTypedDict(TypedDict): + """TypedDict variant of TrackingRefAdjustmentTransaction, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + data_type: NotRequired[Optional[TrackingRefAdjustmentTransactionDataType]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/transaction.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/transaction.py index 8b95d8e8a..4ccef5150 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/transaction.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/transaction.py @@ -1,78 +1,6 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - from __future__ import annotations -from codat_sync_for_expenses.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 TransactionDefinitionsStatus(str, Enum): - r"""Status of transaction.""" - - UNKNOWN = "Unknown" - PUSH_ERROR = "PushError" - COMPLETED = "Completed" - FAILED = "Failed" - PENDING = "Pending" - - -class TransactionTypedDict(TypedDict): - error_message: NotRequired[Nullable[str]] - r"""Error message for failed transaction.""" - id: NotRequired[str] - r"""Unique identifier of the transaction.""" - status: NotRequired[TransactionDefinitionsStatus] - r"""Status of transaction.""" - -class Transaction(BaseModel): - error_message: Annotated[ - OptionalNullable[str], pydantic.Field(alias="errorMessage") - ] = UNSET - r"""Error message for failed transaction.""" - - id: Optional[str] = None - r"""Unique identifier of the transaction.""" - - status: Optional[TransactionDefinitionsStatus] = None - r"""Status of transaction.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["errorMessage", "id", "status"]) - nullable_fields = set(["errorMessage"]) - 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 +from enum import Enum -try: - Transaction.model_rebuild() -except NameError: - pass +from codat_sync_for_expenses.models._compat.transaction import TransactionDefinitionsStatus diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/transactions.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/transactions.py index e5e7f1b86..70f562863 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/transactions.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/transactions.py @@ -1,58 +1,138 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + from __future__ import annotations -from .links import Links, LinksTypedDict -from .schema_transaction import SchemaTransaction, SchemaTransactionTypedDict -from codat_sync_for_expenses.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_expenses.models.shared.links import Links, LinksTypedDict +from codat_sync_for_expenses.models.shared.schema_transaction import SchemaTransaction, SchemaTransactionTypedDict +from typing import Optional, Set +from typing_extensions import Self +class Transactions(BaseModel): -class TransactionsTypedDict(TypedDict): - links: LinksTypedDict - 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.""" - results: NotRequired[List[SchemaTransactionTypedDict]] + @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} + """ + Transactions + """ # 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[SchemaTransaction]] = None + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["pageNumber", "pageSize", "totalResults", "_links", "results"] + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) -class Transactions(BaseModel): - links: Annotated[Links, pydantic.Field(alias="_links")] - page_number: Annotated[int, pydantic.Field(alias="pageNumber")] - r"""Current page number.""" + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - page_size: Annotated[int, pydantic.Field(alias="pageSize")] - r"""Number of items to return in results array.""" + 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()) - total_results: Annotated[int, pydantic.Field(alias="totalResults")] - r"""Total number of items.""" + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of Transactions from a JSON string""" + return cls.from_dict(json.loads(json_str)) - results: Optional[List[SchemaTransaction]] = 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. + * 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 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 + # 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 - for n, f in type(self).model_fields.items(): - k = f.alias or n - val = serialized.get(k, serialized.get(n)) + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of Transactions from a dict""" + if obj is None: + return None - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val + if not isinstance(obj, dict): + return cls.model_validate(obj) - return m + _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": [SchemaTransaction.from_dict(_item) for _item in obj["results"]] if obj.get("results") is not None else None + }) + # 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 -try: - Transactions.model_rebuild() -except NameError: - pass + + + + +class TransactionsTypedDict(TypedDict): + """TypedDict variant of Transactions, 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[SchemaTransactionTypedDict]]] + additional_properties: NotRequired[Dict[str, Any]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/transactionstatus.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/transactionstatus.py index a6a2deccc..c84989c06 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/transactionstatus.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/transactionstatus.py @@ -1,14 +1,40 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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 TransactionStatus(str, Enum): - r"""Status of the transaction.""" + """ + Status of the transaction. + """ + + """ + allowed enum values + """ + UNKNOWN = 'Unknown' + PENDING = 'Pending' + VALIDATION_ERROR = 'ValidationError' + COMPLETED = 'Completed' + PUSH_ERROR = 'PushError' + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of TransactionStatus from a JSON string""" + return cls(json.loads(json_str)) + - UNKNOWN = "Unknown" - PENDING = "Pending" - VALIDATION_ERROR = "ValidationError" - COMPLETED = "Completed" - PUSH_ERROR = "PushError" diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/transfertransactionrequest.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/transfertransactionrequest.py index 97bd0be80..e58e41d20 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/transfertransactionrequest.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/transfertransactionrequest.py @@ -1,129 +1,116 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -from codat_sync_for_expenses.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 AccountReferenceTypedDict(TypedDict): - r"""Reference of the account you are transferring money from.""" - - id: str - r"""'id' from the Accounts data type.""" - - -class AccountReference(BaseModel): - r"""Reference of the account you are transferring money from.""" - - id: str - r"""'id' from the Accounts data type.""" +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class FromTypedDict(TypedDict): - account_ref: AccountReferenceTypedDict - r"""Reference of the account you are transferring money from.""" - amount: Decimal - r"""Amount that has been transferred from the account in the native currency of the account.""" + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class From(BaseModel): - account_ref: Annotated[AccountReference, pydantic.Field(alias="accountRef")] - r"""Reference of the account you are transferring money from.""" - amount: Annotated[ - Decimal, - BeforeValidator(validate_decimal), - PlainSerializer(serialize_decimal(False)), - ] - r"""Amount that has been transferred from the account in the native currency of the account.""" - - -class TransferTransactionRequestAccountReferenceTypedDict(TypedDict): - r"""Reference of the account you are transferring money to.""" - - id: str - r"""'id' from the Accounts data type.""" - - -class TransferTransactionRequestAccountReference(BaseModel): - r"""Reference of the account you are transferring money to.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - id: str - r"""'id' from the Accounts data type.""" +from pydantic import BaseModel, ConfigDict, Field, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_sync_for_expenses.models.transfer_transaction_request_from import TransferTransactionRequestFrom, TransferTransactionRequestFromTypedDict +from codat_sync_for_expenses.models.transfer_transaction_request_to import TransferTransactionRequestTo, TransferTransactionRequestToTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict +class TransferTransactionRequest(BaseModel): -class ToTypedDict(TypedDict): - account_ref: TransferTransactionRequestAccountReferenceTypedDict - r"""Reference of the account you are transferring money to.""" - amount: Decimal - r"""Amount that has been transferred to the account in the native currency of the account.""" + @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} + """ + TransferTransactionRequest + """ # noqa: E501 + description: Optional[str] = Field(default=None, description="Any private, company notes about the transaction.") + date_: str = Field(description="Date of the transfer transaction as recorded in the accounting software.", alias="date") + from_: TransferTransactionRequestFrom = Field(alias="from") + to: TransferTransactionRequestTo + __properties: ClassVar[List[str]] = ["description", "date", "from", "to"] + + 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 TransferTransactionRequest 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 var_from + if self.from_: + _dict['from'] = self.from_.to_dict() + # override the default output from pydantic by calling `to_dict()` of to + if self.to: + _dict['to'] = self.to.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TransferTransactionRequest 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"), + "date": obj.get("date"), + "from": TransferTransactionRequestFrom.from_dict(obj["from"]) if obj.get("from") is not None else None, + "to": TransferTransactionRequestTo.from_dict(obj["to"]) if obj.get("to") is not None else None + }) + return _obj -class To(BaseModel): - account_ref: Annotated[ - TransferTransactionRequestAccountReference, pydantic.Field(alias="accountRef") - ] - r"""Reference of the account you are transferring money to.""" - amount: Annotated[ - Decimal, - BeforeValidator(validate_decimal), - PlainSerializer(serialize_decimal(False)), - ] - r"""Amount that has been transferred to the account in the native currency of the account.""" class TransferTransactionRequestTypedDict(TypedDict): - date_: str - from_: FromTypedDict - to: ToTypedDict - description: NotRequired[str] - r"""Any private, company notes about the transaction.""" - - -class TransferTransactionRequest(BaseModel): - date_: Annotated[str, pydantic.Field(alias="date")] - - from_: Annotated[From, pydantic.Field(alias="from")] - - to: To - - description: Optional[str] = None - r"""Any private, company notes about the transaction.""" - - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["description"]) - 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: - From.model_rebuild() -except NameError: - pass -try: - To.model_rebuild() -except NameError: - pass -try: - TransferTransactionRequest.model_rebuild() -except NameError: - pass + """TypedDict variant of TransferTransactionRequest, for dict-literal request/response inputs.""" + description: NotRequired[Optional[str]] + date_: NotRequired[str] + from_: NotRequired[TransferTransactionRequestFromTypedDict] + to: TransferTransactionRequestToTypedDict diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/transfertransactionresponse.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/transfertransactionresponse.py index e82dde4c4..6d4c4f74d 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/transfertransactionresponse.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/transfertransactionresponse.py @@ -1,40 +1,99 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class TransferTransactionResponseTypedDict(TypedDict): - sync_id: NotRequired[str] - r"""Unique id of sync created""" + The version of the OpenAPI document: prealpha + Contact: expenses@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 TransferTransactionResponse(BaseModel): - sync_id: Annotated[Optional[str], pydantic.Field(alias="syncId")] = None - r"""Unique id of sync created""" @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["syncId"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + TransferTransactionResponse + """ # noqa: E501 + sync_id: Optional[str] = Field(default=None, description="Unique id of sync created", alias="syncId") + __properties: ClassVar[List[str]] = ["syncId"] + + 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 TransferTransactionResponse 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: - TransferTransactionResponse.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 TransferTransactionResponse from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "syncId": obj.get("syncId") + }) + return _obj + + + + + +class TransferTransactionResponseTypedDict(TypedDict): + """TypedDict variant of TransferTransactionResponse, for dict-literal request/response inputs.""" + sync_id: NotRequired[Optional[str]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/updatecustomerresponse.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/updatecustomerresponse.py index dbf983c71..17faaef24 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/updatecustomerresponse.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/updatecustomerresponse.py @@ -1,417 +1,171 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .contact import Contact, ContactTypedDict -from .customerstatus import CustomerStatus -from .datatype import DataType -from .items import Items, ItemsTypedDict -from .metadata import Metadata, MetadataTypedDict -from .pushoperationchange import PushOperationChange, PushOperationChangeTypedDict -from .pushoperationstatus import PushOperationStatus -from .supplementaldata import SupplementalData, SupplementalDataTypedDict -from .validation import Validation, ValidationTypedDict -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict, deprecated - - -@deprecated( - "warning: ** DEPRECATED ** - This will be removed in a future release, please migrate away from it as soon as possible." -) -class UpdateCustomerResponseAccountingCustomerTypedDict(TypedDict): - r"""## Overview - - A customer is a person or organisation that buys goods or services. From the Customers endpoints, you can retrieve a [list of all the customers of a company](https://api.codat.io/swagger/index.html#/Customers/get_companies__companyId__data_customers). - - Customers' data links to accounts receivable [invoices](https://docs.codat.io/sync-for-expenses-api#/schemas/Invoice). - - """ - - status: CustomerStatus - r"""Status of customer.""" - addresses: NotRequired[Nullable[List[ItemsTypedDict]]] - r"""An array of Addresses.""" - contact_name: NotRequired[Nullable[str]] - r"""Name of the main contact for the identified customer.""" - contacts: NotRequired[Nullable[List[ContactTypedDict]]] - r"""An array of Contacts.""" - customer_name: NotRequired[Nullable[str]] - r"""Name of the customer as recorded in the accounting system, typically the company name.""" - default_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. - """ - email_address: NotRequired[Nullable[str]] - r"""Email address the customer can be contacted by.""" - id: NotRequired[str] - r"""Identifier for the customer, unique to the company in the accounting software.""" - metadata: NotRequired[MetadataTypedDict] - modified_date: NotRequired[str] - phone: NotRequired[Nullable[str]] - r"""Phone number the customer can be contacted by.""" - registration_number: NotRequired[Nullable[str]] - r"""Company number. In the UK, this is typically the Companies House company registration number.""" - source_modified_date: NotRequired[str] - supplemental_data: NotRequired[SupplementalDataTypedDict] - r"""Supplemental data is additional data you can include in our standard data types. - - It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. - """ - tax_number: NotRequired[Nullable[str]] - r"""Company tax number.""" - - -@deprecated( - "warning: ** DEPRECATED ** - This will be removed in a future release, please migrate away from it as soon as possible." -) -class UpdateCustomerResponseAccountingCustomer(BaseModel): - r"""## Overview - - A customer is a person or organisation that buys goods or services. From the Customers endpoints, you can retrieve a [list of all the customers of a company](https://api.codat.io/swagger/index.html#/Customers/get_companies__companyId__data_customers). - - Customers' data links to accounts receivable [invoices](https://docs.codat.io/sync-for-expenses-api#/schemas/Invoice). - - """ - - status: CustomerStatus - r"""Status of customer.""" - - addresses: OptionalNullable[List[Items]] = UNSET - r"""An array of Addresses.""" - - contact_name: Annotated[ - OptionalNullable[str], pydantic.Field(alias="contactName") - ] = UNSET - r"""Name of the main contact for the identified customer.""" +""" + Expenses - contacts: OptionalNullable[List[Contact]] = UNSET - r"""An array of Contacts.""" + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | - customer_name: Annotated[ - OptionalNullable[str], pydantic.Field(alias="customerName") - ] = UNSET - r"""Name of the customer as recorded in the accounting system, typically the company name.""" + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - default_currency: Annotated[ - Optional[str], pydantic.Field(alias="defaultCurrency") - ] = None - 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. - - There are only a very small number of edge cases where this currency code is returned by the Codat system. - """ - - email_address: Annotated[ - OptionalNullable[str], pydantic.Field(alias="emailAddress") - ] = UNSET - r"""Email address the customer can be contacted by.""" - - id: Optional[str] = None - r"""Identifier for the customer, unique to the company in the accounting software.""" - - metadata: Optional[Metadata] = None - - modified_date: Annotated[Optional[str], pydantic.Field(alias="modifiedDate")] = None - - phone: OptionalNullable[str] = UNSET - r"""Phone number the customer can be contacted by.""" - - registration_number: Annotated[ - OptionalNullable[str], pydantic.Field(alias="registrationNumber") - ] = UNSET - r"""Company number. In the UK, this is typically the Companies House company registration number.""" - - source_modified_date: Annotated[ - Optional[str], pydantic.Field(alias="sourceModifiedDate") - ] = None - - supplemental_data: Annotated[ - Optional[SupplementalData], pydantic.Field(alias="supplementalData") - ] = None - r"""Supplemental data is additional data you can include in our standard data types. - - It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. - """ - - tax_number: Annotated[OptionalNullable[str], pydantic.Field(alias="taxNumber")] = ( - UNSET - ) - r"""Company tax number.""" +from __future__ import annotations +from codat_sync_for_expenses.models.shared.datatype 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_expenses.models.shared.pushoperationchange import PushOperationChange, PushOperationChangeTypedDict +from codat_sync_for_expenses.models.shared.pushoperationstatus import PushOperationStatus +from codat_sync_for_expenses.models.update_customer_response_all_of_data import UpdateCustomerResponseAllOfData +from codat_sync_for_expenses.models.shared.validation import Validation, ValidationTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL +class UpdateCustomerResponse(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "addresses", - "contactName", - "contacts", - "customerName", - "defaultCurrency", - "emailAddress", - "id", - "metadata", - "modifiedDate", - "phone", - "registrationNumber", - "sourceModifiedDate", - "supplementalData", - "taxNumber", - ] - ) - nullable_fields = set( - [ - "addresses", - "contactName", - "contacts", - "customerName", - "emailAddress", - "phone", - "registrationNumber", - "taxNumber", - ] - ) + 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 - - -class UpdateCustomerResponseTypedDict(TypedDict): - company_id: str - r"""Unique identifier for your SMB in Codat.""" - data_connection_key: str - r"""Unique identifier for a company's data connection.""" - push_operation_key: str - r"""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 - 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. - """ - status: PushOperationStatus - r"""The current status of the push operation.""" - status_code: int - r"""Push status code.""" - changes: NotRequired[Nullable[List[PushOperationChangeTypedDict]]] - r"""Contains a single entry that communicates which record has changed and the manner in which it changed.""" - completed_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. - """ - data: NotRequired[Nullable[UpdateCustomerResponseAccountingCustomerTypedDict]] - data_type: NotRequired[DataType] - r"""Available data types""" - error_message: NotRequired[Nullable[str]] - r"""A message about the error.""" - timeout_in_minutes: NotRequired[Nullable[int]] - r"""Number of minutes the push operation must complete within before it times out.""" - timeout_in_seconds: NotRequired[Nullable[int]] - r"""Number of seconds the push operation must complete within before it times out.""" - validation: NotRequired[ValidationTypedDict] - r"""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.""" - - -class UpdateCustomerResponse(BaseModel): - company_id: Annotated[str, pydantic.Field(alias="companyId")] - r"""Unique identifier for your SMB in Codat.""" - - data_connection_key: Annotated[str, pydantic.Field(alias="dataConnectionKey")] - r"""Unique identifier for a company's data connection.""" - - push_operation_key: Annotated[str, pydantic.Field(alias="pushOperationKey")] - r"""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: Annotated[str, pydantic.Field(alias="requestedOnUtc")] - 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. + _nullable = {'changes', 'data', 'errorMessage', 'error_message', 'timeoutInMinutes', 'timeoutInSeconds', 'timeout_in_minutes', 'timeout_in_seconds'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } """ - + UpdateCustomerResponse + """ # noqa: E501 + changes: OptionalNullable[List[PushOperationChange]] = Field(default=UNSET, description="Contains a single entry that communicates which record has changed and the manner in which it changed. ") + data_type: Optional[DataType] = 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="The datetime when the push was requested.", alias="requestedOnUtc") + completed_on_utc: Optional[str] = Field(default=None, description="The datetime when the push was completed, null if Pending.", alias="completedOnUtc") + timeout_in_minutes: OptionalNullable[int] = Field(default=UNSET, description="Number of minutes the push operation must complete within before it times out.", alias="timeoutInMinutes") + timeout_in_seconds: OptionalNullable[int] = Field(default=UNSET, description="Number of seconds the push operation must complete within before it times out.", alias="timeoutInSeconds") status: PushOperationStatus - r"""The current status of the push operation.""" - - status_code: Annotated[int, pydantic.Field(alias="statusCode")] - r"""Push status code.""" - - changes: OptionalNullable[List[PushOperationChange]] = UNSET - r"""Contains a single entry that communicates which record has changed and the manner in which it changed.""" - - completed_on_utc: Annotated[ - Optional[str], pydantic.Field(alias="completedOnUtc") - ] = 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` + error_message: OptionalNullable[str] = Field(default=UNSET, description="A message about the error.", alias="errorMessage") + validation: Optional[Validation] = None + status_code: int = Field(description="Push status code.", alias="statusCode") + data: OptionalNullable[UpdateCustomerResponseAllOfData] = UNSET + __properties: ClassVar[List[str]] = ["changes", "dataType", "companyId", "pushOperationKey", "dataConnectionKey", "requestedOnUtc", "completedOnUtc", "timeoutInMinutes", "timeoutInSeconds", "status", "errorMessage", "validation", "statusCode", "data"] + + @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=(), + ) - > 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: OptionalNullable[UpdateCustomerResponseAccountingCustomer] = UNSET + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - data_type: Annotated[Optional[DataType], pydantic.Field(alias="dataType")] = None - r"""Available data types""" + 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()) - error_message: Annotated[ - OptionalNullable[str], pydantic.Field(alias="errorMessage") - ] = UNSET - r"""A message about the error.""" + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of UpdateCustomerResponse from a JSON string""" + return cls.from_dict(json.loads(json_str)) - timeout_in_minutes: Annotated[ - OptionalNullable[int], pydantic.Field(alias="timeoutInMinutes") - ] = UNSET - r"""Number of minutes the push operation must complete within before it times out.""" + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - timeout_in_seconds: Annotated[ - OptionalNullable[int], - pydantic.Field( - deprecated="warning: ** DEPRECATED ** - This will be removed in a future release, please migrate away from it as soon as possible.", - alias="timeoutInSeconds", - ), - ] = UNSET - r"""Number of seconds the push operation must complete within before it times out.""" + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - validation: Optional[Validation] = None - r"""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.""" + * `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( - [ - "changes", - "completedOnUtc", - "data", - "dataType", - "errorMessage", - "timeoutInMinutes", - "timeoutInSeconds", - "validation", - ] - ) - nullable_fields = set( - ["changes", "data", "errorMessage", "timeoutInMinutes", "timeoutInSeconds"] + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, ) - serialized = handler(self) - m = {} + # 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() + # override the default output from pydantic by calling `to_dict()` of data + if self.data: + _dict['data'] = self.data.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of UpdateCustomerResponse 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"), + "data": UpdateCustomerResponseAllOfData.from_dict(obj["data"]) if obj.get("data") is not None else None + }) + return _obj - 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: - UpdateCustomerResponseAccountingCustomer.model_rebuild() -except NameError: - pass -try: - UpdateCustomerResponse.model_rebuild() -except NameError: - pass +class UpdateCustomerResponseTypedDict(TypedDict): + """TypedDict variant of UpdateCustomerResponse, for dict-literal request/response inputs.""" + changes: NotRequired[Optional[List[PushOperationChangeTypedDict]]] + data_type: NotRequired[Optional[DataType]] + 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] + data: NotRequired[Optional[UpdateCustomerResponseAllOfData]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/updateexpenserequest.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/updateexpenserequest.py index 04ea6b6a8..45e3fc3d7 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/updateexpenserequest.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/updateexpenserequest.py @@ -1,221 +1,154 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .expensecontactref import ExpenseContactRef, ExpenseContactRefTypedDict -from .expensetransactionline import ( - ExpenseTransactionLine, - ExpenseTransactionLineTypedDict, -) -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from codat_sync_for_expenses.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 List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class UpdateExpenseRequestBankAccountReferenceTypedDict(TypedDict): - id: NotRequired[str] - r"""Identifier of the bank account.""" + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class UpdateExpenseRequestBankAccountReference(BaseModel): - id: Optional[str] = None - r"""Identifier of the bank account.""" + +from __future__ import annotations +from decimal import Decimal +from codat_sync_for_expenses.utils.serializers import serialize_decimal, validate_decimal +from codat_sync_for_expenses.models.update_expense_request_type import UpdateExpenseRequestType +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 codat_sync_for_expenses.models.bank_account_reference import BankAccountReference, BankAccountReferenceTypedDict +from codat_sync_for_expenses.models.expense_contact_ref import ExpenseContactRef, ExpenseContactRefTypedDict +from codat_sync_for_expenses.models.shared.expensetransactionline import ExpenseTransactionLine, ExpenseTransactionLineTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL +class UpdateExpenseRequest(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["id"]) + 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)) - - if val != UNSET_SENTINEL: - if val is not None or k not in optional_fields: - m[k] = val - - return m - - -class UpdateExpenseRequestType(str, Enum): - r"""The type of transaction.""" - - PAYMENT = "Payment" - REFUND = "Refund" - REWARD = "Reward" - CHARGEBACK = "Chargeback" - - -class UpdateExpenseRequestTypedDict(TypedDict): - currency: str - r"""Currency the transaction was recorded in.""" - issue_date: str - r"""Date the transaction was recorded.""" - type: UpdateExpenseRequestType - r"""The type of transaction.""" - bank_account_ref: NotRequired[UpdateExpenseRequestBankAccountReferenceTypedDict] - contact_ref: NotRequired[ExpenseContactRefTypedDict] - 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. - - ## 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. | + _nullable = {'currencyRate', 'currency_rate'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } """ - lines: NotRequired[List[ExpenseTransactionLineTypedDict]] - r"""Array of transaction lines.""" - merchant_name: NotRequired[str] - r"""Name of the merchant where the purchase took place""" - notes: NotRequired[str] - r"""Any private, company notes about the transaction.""" - - -class UpdateExpenseRequest(BaseModel): - currency: str - r"""Currency the transaction was recorded in.""" - - issue_date: Annotated[str, pydantic.Field(alias="issueDate")] - r"""Date the transaction was recorded.""" - - type: UpdateExpenseRequestType - r"""The type of transaction.""" - - bank_account_ref: Annotated[ - Optional[UpdateExpenseRequestBankAccountReference], - pydantic.Field(alias="bankAccountRef"), - ] = None - - contact_ref: Annotated[ - Optional[ExpenseContactRef], pydantic.Field(alias="contactRef") - ] = None - - 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 | - - - ### Integration-specific details + UpdateExpenseRequest + """ # noqa: E501 + type: UpdateExpenseRequestType = Field(description="The type of transaction.") + issue_date: str = Field(description="Date the transaction was recorded.", alias="issueDate") + currency: str = Field(description="Currency the transaction was recorded in.") + 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") + contact_ref: Optional[ExpenseContactRef] = Field(default=None, description="Supplier or Customer for the purchase to be associated to.", alias="contactRef") + bank_account_ref: Optional[BankAccountReference] = Field(default=None, alias="bankAccountRef") + merchant_name: Optional[str] = Field(default=None, description="Name of the merchant where the purchase took place", alias="merchantName") + lines: Optional[List[ExpenseTransactionLine]] = Field(default=None, description="Array of transaction lines.") + notes: Optional[str] = Field(default=None, description="Any private, company notes about the transaction.") + __properties: ClassVar[List[str]] = ["type", "issueDate", "currency", "currencyRate", "contactRef", "bankAccountRef", "merchantName", "lines", "notes"] + + @field_validator('type') + def type_validate_enum(cls, value): + """Validates the enum""" + if value not in set(['Payment', 'Refund', 'Reward', 'Chargeback']): + raise ValueError("must be one of enum values ('Payment', 'Refund', 'Reward', 'Chargeback')") + 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 UpdateExpenseRequest 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 contact_ref + if self.contact_ref: + _dict['contactRef'] = self.contact_ref.to_dict() + # override the default output from pydantic by calling `to_dict()` of bank_account_ref + if self.bank_account_ref: + _dict['bankAccountRef'] = self.bank_account_ref.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in lines (list) + _items = [] + if self.lines: + for _item_lines in self.lines: + if _item_lines: + _items.append(_item_lines.to_dict()) + _dict['lines'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of UpdateExpenseRequest 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"), + "issueDate": obj.get("issueDate"), + "currency": obj.get("currency"), + "currencyRate": obj.get("currencyRate"), + "contactRef": ExpenseContactRef.from_dict(obj["contactRef"]) if obj.get("contactRef") is not None else None, + "bankAccountRef": BankAccountReference.from_dict(obj["bankAccountRef"]) if obj.get("bankAccountRef") is not None else None, + "merchantName": obj.get("merchantName"), + "lines": [ExpenseTransactionLine.from_dict(_item) for _item in obj["lines"]] if obj.get("lines") is not None else None, + "notes": obj.get("notes") + }) + return _obj - | 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. | - """ - lines: Optional[List[ExpenseTransactionLine]] = None - r"""Array of transaction lines.""" - merchant_name: Annotated[Optional[str], pydantic.Field(alias="merchantName")] = None - r"""Name of the merchant where the purchase took place""" - notes: Optional[str] = None - r"""Any private, company notes about the transaction.""" - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "bankAccountRef", - "contactRef", - "currencyRate", - "lines", - "merchantName", - "notes", - ] - ) - nullable_fields = set(["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: - UpdateExpenseRequest.model_rebuild() -except NameError: - pass +class UpdateExpenseRequestTypedDict(TypedDict): + """TypedDict variant of UpdateExpenseRequest, for dict-literal request/response inputs.""" + type: NotRequired[UpdateExpenseRequestType] + issue_date: NotRequired[str] + currency: NotRequired[str] + currency_rate: NotRequired[Optional[Decimal]] + contact_ref: NotRequired[Optional[ExpenseContactRefTypedDict]] + bank_account_ref: NotRequired[Optional[BankAccountReferenceTypedDict]] + merchant_name: NotRequired[Optional[str]] + lines: NotRequired[Optional[List[ExpenseTransactionLineTypedDict]]] + notes: NotRequired[Optional[str]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/updateexpenseresponse.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/updateexpenseresponse.py index 577f1e23a..e49e20d55 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/updateexpenseresponse.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/updateexpenseresponse.py @@ -1,40 +1,99 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_expenses.types import BaseModel, UNSET_SENTINEL -import pydantic -from pydantic import model_serializer -from typing import Optional -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class UpdateExpenseResponseTypedDict(TypedDict): - sync_id: NotRequired[str] - r"""Unique identifier for the update expense sync.""" + The version of the OpenAPI document: prealpha + Contact: expenses@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 UpdateExpenseResponse(BaseModel): - sync_id: Annotated[Optional[str], pydantic.Field(alias="syncId")] = None - r"""Unique identifier for the update expense sync.""" @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set(["syncId"]) + def _serialize_drop_none(self, handler): serialized = handler(self) - m = {} + return {k: v for k, v in serialized.items() if v is not None} + """ + UpdateExpenseResponse + """ # noqa: E501 + sync_id: Optional[str] = Field(default=None, description="Unique identifier for the update expense sync.", alias="syncId") + __properties: ClassVar[List[str]] = ["syncId"] + + 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 UpdateExpenseResponse 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: - UpdateExpenseResponse.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 UpdateExpenseResponse from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "syncId": obj.get("syncId") + }) + return _obj + + + + + +class UpdateExpenseResponseTypedDict(TypedDict): + """TypedDict variant of UpdateExpenseResponse, for dict-literal request/response inputs.""" + sync_id: NotRequired[Optional[str]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/updatereimbursableexpensetransactionrequest.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/updatereimbursableexpensetransactionrequest.py index b7cb475e2..6a944bf92 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/updatereimbursableexpensetransactionrequest.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/updatereimbursableexpensetransactionrequest.py @@ -1,255 +1,147 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from __future__ import annotations -from .apaccountref import ApAccountRef, ApAccountRefTypedDict -from .reimbursableexpensetransactionline import ( - ReimbursableExpenseTransactionLine, - ReimbursableExpenseTransactionLineTypedDict, -) -from .reimbursementcontactref import ( - ReimbursementContactRef, - ReimbursementContactRefTypedDict, -) -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from codat_sync_for_expenses.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 UpdateReimbursableExpenseTransactionRequestTypedDict(TypedDict): - contact_ref: ReimbursementContactRefTypedDict - currency: str - r"""Currency the transaction was recorded in.""" - due_date: 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 - ``` - +# coding: utf-8 +""" + Expenses - When syncing data that contains `DateTime` fields from Codat, make sure you support the following cases when reading time information: + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | - - 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` + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - > 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. - """ - issue_date: 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. - """ - ap_account_ref: NotRequired[Nullable[ApAccountRefTypedDict]] - 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. + Do not edit the class manually. +""" # noqa: E501 - 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. | - """ - lines: NotRequired[List[ReimbursableExpenseTransactionLineTypedDict]] - r"""Array of transaction lines.""" - notes: NotRequired[str] - r"""Any private, company notes about the transaction.""" - reference: NotRequired[Nullable[str]] - r"""User-friendly reference for the reimbursable expense.""" +from __future__ import annotations +from decimal import Decimal +from codat_sync_for_expenses.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 Any, ClassVar, Dict, List, Optional, Union +from typing_extensions import Annotated, NotRequired, TypedDict +from codat_sync_for_expenses.models.shared.apaccountref import ApAccountRef, ApAccountRefTypedDict +from codat_sync_for_expenses.models.shared.reimbursableexpensetransactionline import ReimbursableExpenseTransactionLine, ReimbursableExpenseTransactionLineTypedDict +from codat_sync_for_expenses.models.shared.reimbursementcontactref import ReimbursementContactRef, ReimbursementContactRefTypedDict +from typing import Optional, Set +from typing_extensions import Self +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL class UpdateReimbursableExpenseTransactionRequest(BaseModel): - contact_ref: Annotated[ReimbursementContactRef, pydantic.Field(alias="contactRef")] - - currency: str - r"""Currency the transaction was recorded in.""" - - due_date: Annotated[str, pydantic.Field(alias="dueDate")] - 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. - """ - - issue_date: Annotated[str, pydantic.Field(alias="issueDate")] - 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 = {'apAccountRef', 'ap_account_ref', '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) + } """ + UpdateReimbursableExpenseTransactionRequest + """ # noqa: E501 + reference: OptionalNullable[str] = Field(default=UNSET, description="User-friendly reference for the reimbursable expense.") + contact_ref: ReimbursementContactRef = Field(alias="contactRef") + ap_account_ref: OptionalNullable[ApAccountRef] = Field(default=UNSET, alias="apAccountRef") + issue_date: str = Field(description="Date of the transaction was recorded.", alias="issueDate") + due_date: str = Field(description="Date the supplier is due to be paid.", alias="dueDate") + currency: str = Field(description="Currency the transaction was recorded in.") + 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") + notes: Optional[str] = Field(default=None, description="Any private, company notes about the transaction.") + lines: Optional[List[ReimbursableExpenseTransactionLine]] = Field(default=None, description="Array of transaction lines.") + __properties: ClassVar[List[str]] = ["reference", "contactRef", "apAccountRef", "issueDate", "dueDate", "currency", "currencyRate", "notes", "lines"] + + 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 UpdateReimbursableExpenseTransactionRequest 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 contact_ref + if self.contact_ref: + _dict['contactRef'] = self.contact_ref.to_dict() + # override the default output from pydantic by calling `to_dict()` of ap_account_ref + if self.ap_account_ref: + _dict['apAccountRef'] = self.ap_account_ref.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in lines (list) + _items = [] + if self.lines: + for _item_lines in self.lines: + if _item_lines: + _items.append(_item_lines.to_dict()) + _dict['lines'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of UpdateReimbursableExpenseTransactionRequest 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"), + "contactRef": ReimbursementContactRef.from_dict(obj["contactRef"]) if obj.get("contactRef") is not None else None, + "apAccountRef": ApAccountRef.from_dict(obj["apAccountRef"]) if obj.get("apAccountRef") is not None else None, + "issueDate": obj.get("issueDate"), + "dueDate": obj.get("dueDate"), + "currency": obj.get("currency"), + "currencyRate": obj.get("currencyRate"), + "notes": obj.get("notes"), + "lines": [ReimbursableExpenseTransactionLine.from_dict(_item) for _item in obj["lines"]] if obj.get("lines") is not None else None + }) + return _obj - ap_account_ref: Annotated[ - OptionalNullable[ApAccountRef], pydantic.Field(alias="apAccountRef") - ] = UNSET - - 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 | - - - ### 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. | - """ - lines: Optional[List[ReimbursableExpenseTransactionLine]] = None - r"""Array of transaction lines.""" - notes: Optional[str] = None - r"""Any private, company notes about the transaction.""" - reference: OptionalNullable[str] = UNSET - r"""User-friendly reference for the reimbursable expense.""" - @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - ["apAccountRef", "currencyRate", "lines", "notes", "reference"] - ) - nullable_fields = set(["apAccountRef", "currencyRate", "reference"]) - 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: - UpdateReimbursableExpenseTransactionRequest.model_rebuild() -except NameError: - pass +class UpdateReimbursableExpenseTransactionRequestTypedDict(TypedDict): + """TypedDict variant of UpdateReimbursableExpenseTransactionRequest, for dict-literal request/response inputs.""" + reference: NotRequired[Optional[str]] + contact_ref: NotRequired[ReimbursementContactRefTypedDict] + ap_account_ref: NotRequired[Optional[ApAccountRefTypedDict]] + issue_date: NotRequired[str] + due_date: NotRequired[str] + currency: NotRequired[str] + currency_rate: NotRequired[Optional[Decimal]] + notes: NotRequired[Optional[str]] + lines: NotRequired[Optional[List[ReimbursableExpenseTransactionLineTypedDict]]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/updatesupplierresponse.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/updatesupplierresponse.py index 94cabc2fc..f398e9470 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/updatesupplierresponse.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/updatesupplierresponse.py @@ -1,390 +1,171 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .datatype import DataType -from .items import Items, ItemsTypedDict -from .metadata import Metadata, MetadataTypedDict -from .pushoperationchange import PushOperationChange, PushOperationChangeTypedDict -from .pushoperationstatus import PushOperationStatus -from .supplementaldata import SupplementalData, SupplementalDataTypedDict -from .supplierstatus import SupplierStatus -from .validation import Validation, ValidationTypedDict -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing import List, Optional -from typing_extensions import Annotated, NotRequired, TypedDict, deprecated - - -@deprecated( - "warning: ** DEPRECATED ** - This will be removed in a future release, please migrate away from it as soon as possible." -) -class UpdateSupplierResponseAccountingSupplierTypedDict(TypedDict): - r"""## Overview - - From the **Suppliers** endpoints, you can retrieve a list of [all the suppliers for a company](https://docs.codat.io/sync-for-expenses-api#/operations/list-suppliers). Suppliers' data links to accounts payable [bills](https://docs.codat.io/sync-for-expenses-api#/schemas/Bill). - """ - - status: SupplierStatus - r"""Status of the supplier.""" - addresses: NotRequired[Nullable[List[ItemsTypedDict]]] - r"""An array of Addresses.""" - contact_name: NotRequired[Nullable[str]] - r"""Name of the main contact for the supplier.""" - default_currency: NotRequired[Nullable[str]] - r"""Default currency the supplier's transactional data is recorded in.""" - email_address: NotRequired[Nullable[str]] - r"""Email address that the supplier may be contacted on.""" - id: NotRequired[str] - r"""Identifier for the supplier, unique to the company in the accounting software.""" - metadata: NotRequired[MetadataTypedDict] - modified_date: NotRequired[str] - phone: NotRequired[Nullable[str]] - r"""Phone number that the supplier may be contacted on.""" - registration_number: NotRequired[Nullable[str]] - r"""Company number of the supplier. In the UK, this is typically the company registration number issued by Companies House.""" - source_modified_date: NotRequired[str] - supplemental_data: NotRequired[SupplementalDataTypedDict] - r"""Supplemental data is additional data you can include in our standard data types. - - It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. - """ - supplier_name: NotRequired[Nullable[str]] - r"""Name of the supplier as recorded in the accounting system, typically the company name.""" - tax_number: NotRequired[Nullable[str]] - r"""Supplier's company tax number.""" - - -@deprecated( - "warning: ** DEPRECATED ** - This will be removed in a future release, please migrate away from it as soon as possible." -) -class UpdateSupplierResponseAccountingSupplier(BaseModel): - r"""## Overview - - From the **Suppliers** endpoints, you can retrieve a list of [all the suppliers for a company](https://docs.codat.io/sync-for-expenses-api#/operations/list-suppliers). Suppliers' data links to accounts payable [bills](https://docs.codat.io/sync-for-expenses-api#/schemas/Bill). - """ - - status: SupplierStatus - r"""Status of the supplier.""" - - addresses: OptionalNullable[List[Items]] = UNSET - r"""An array of Addresses.""" - - contact_name: Annotated[ - OptionalNullable[str], pydantic.Field(alias="contactName") - ] = UNSET - r"""Name of the main contact for the supplier.""" - - default_currency: Annotated[ - OptionalNullable[str], pydantic.Field(alias="defaultCurrency") - ] = UNSET - r"""Default currency the supplier's transactional data is recorded in.""" - - email_address: Annotated[ - OptionalNullable[str], pydantic.Field(alias="emailAddress") - ] = UNSET - r"""Email address that the supplier may be contacted on.""" - - id: Optional[str] = None - r"""Identifier for the supplier, unique to the company in the accounting software.""" - - metadata: Optional[Metadata] = None - - modified_date: Annotated[Optional[str], pydantic.Field(alias="modifiedDate")] = None +""" + Expenses - phone: OptionalNullable[str] = UNSET - r"""Phone number that the supplier may be contacted on.""" + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | - registration_number: Annotated[ - OptionalNullable[str], pydantic.Field(alias="registrationNumber") - ] = UNSET - r"""Company number of the supplier. In the UK, this is typically the company registration number issued by Companies House.""" + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - source_modified_date: Annotated[ - Optional[str], pydantic.Field(alias="sourceModifiedDate") - ] = None + Do not edit the class manually. +""" # noqa: E501 - supplemental_data: Annotated[ - Optional[SupplementalData], pydantic.Field(alias="supplementalData") - ] = None - r"""Supplemental data is additional data you can include in our standard data types. - It is referenced as a configured dynamic key value pair that is unique to the accounting software. [Learn more](https://docs.codat.io/using-the-api/supplemental-data/overview) about supplemental data. - """ - - supplier_name: Annotated[ - OptionalNullable[str], pydantic.Field(alias="supplierName") - ] = UNSET - r"""Name of the supplier as recorded in the accounting system, typically the company name.""" - - tax_number: Annotated[OptionalNullable[str], pydantic.Field(alias="taxNumber")] = ( - UNSET - ) - r"""Supplier's company tax number.""" +from __future__ import annotations +from codat_sync_for_expenses.models.shared.datatype 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_expenses.models.shared.pushoperationchange import PushOperationChange, PushOperationChangeTypedDict +from codat_sync_for_expenses.models.shared.pushoperationstatus import PushOperationStatus +from codat_sync_for_expenses.models.update_supplier_response_all_of_data import UpdateSupplierResponseAllOfData +from codat_sync_for_expenses.models.shared.validation import Validation, ValidationTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL +class UpdateSupplierResponse(BaseModel): @model_serializer(mode="wrap") - def serialize_model(self, handler): - optional_fields = set( - [ - "addresses", - "contactName", - "defaultCurrency", - "emailAddress", - "id", - "metadata", - "modifiedDate", - "phone", - "registrationNumber", - "sourceModifiedDate", - "supplementalData", - "supplierName", - "taxNumber", - ] - ) - nullable_fields = set( - [ - "addresses", - "contactName", - "defaultCurrency", - "emailAddress", - "phone", - "registrationNumber", - "supplierName", - "taxNumber", - ] - ) + 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 - - -class UpdateSupplierResponseTypedDict(TypedDict): - company_id: str - r"""Unique identifier for your SMB in Codat.""" - data_connection_key: str - r"""Unique identifier for a company's data connection.""" - push_operation_key: str - r"""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 - 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. + _nullable = {'changes', 'data', 'errorMessage', 'error_message', 'timeoutInMinutes', 'timeoutInSeconds', 'timeout_in_minutes', 'timeout_in_seconds'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } """ + UpdateSupplierResponse + """ # noqa: E501 + changes: OptionalNullable[List[PushOperationChange]] = Field(default=UNSET, description="Contains a single entry that communicates which record has changed and the manner in which it changed. ") + data_type: Optional[DataType] = 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="The datetime when the push was requested.", alias="requestedOnUtc") + completed_on_utc: Optional[str] = Field(default=None, description="The datetime when the push was completed, null if Pending.", alias="completedOnUtc") + timeout_in_minutes: OptionalNullable[int] = Field(default=UNSET, description="Number of minutes the push operation must complete within before it times out.", alias="timeoutInMinutes") + timeout_in_seconds: OptionalNullable[int] = Field(default=UNSET, description="Number of seconds the push operation must complete within before it times out.", alias="timeoutInSeconds") status: PushOperationStatus - r"""The current status of the push operation.""" - status_code: int - r"""Push status code.""" - changes: NotRequired[Nullable[List[PushOperationChangeTypedDict]]] - r"""Contains a single entry that communicates which record has changed and the manner in which it changed.""" - completed_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. - """ - data: NotRequired[Nullable[UpdateSupplierResponseAccountingSupplierTypedDict]] - data_type: NotRequired[DataType] - r"""Available data types""" - error_message: NotRequired[Nullable[str]] - r"""A message about the error.""" - timeout_in_minutes: NotRequired[Nullable[int]] - r"""Number of minutes the push operation must complete within before it times out.""" - timeout_in_seconds: NotRequired[Nullable[int]] - r"""Number of seconds the push operation must complete within before it times out.""" - validation: NotRequired[ValidationTypedDict] - r"""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.""" - - -class UpdateSupplierResponse(BaseModel): - company_id: Annotated[str, pydantic.Field(alias="companyId")] - r"""Unique identifier for your SMB in Codat.""" - - data_connection_key: Annotated[str, pydantic.Field(alias="dataConnectionKey")] - r"""Unique identifier for a company's data connection.""" - - push_operation_key: Annotated[str, pydantic.Field(alias="pushOperationKey")] - r"""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: Annotated[str, pydantic.Field(alias="requestedOnUtc")] - 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. - """ - - status: PushOperationStatus - r"""The current status of the push operation.""" - - status_code: Annotated[int, pydantic.Field(alias="statusCode")] - r"""Push status code.""" - - changes: OptionalNullable[List[PushOperationChange]] = UNSET - r"""Contains a single entry that communicates which record has changed and the manner in which it changed.""" - - completed_on_utc: Annotated[ - Optional[str], pydantic.Field(alias="completedOnUtc") - ] = 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` + error_message: OptionalNullable[str] = Field(default=UNSET, description="A message about the error.", alias="errorMessage") + validation: Optional[Validation] = None + status_code: int = Field(description="Push status code.", alias="statusCode") + data: OptionalNullable[UpdateSupplierResponseAllOfData] = UNSET + __properties: ClassVar[List[str]] = ["changes", "dataType", "companyId", "pushOperationKey", "dataConnectionKey", "requestedOnUtc", "completedOnUtc", "timeoutInMinutes", "timeoutInSeconds", "status", "errorMessage", "validation", "statusCode", "data"] + + @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=(), + ) - > 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: OptionalNullable[UpdateSupplierResponseAccountingSupplier] = UNSET + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - data_type: Annotated[Optional[DataType], pydantic.Field(alias="dataType")] = None - r"""Available data types""" + 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()) - error_message: Annotated[ - OptionalNullable[str], pydantic.Field(alias="errorMessage") - ] = UNSET - r"""A message about the error.""" + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of UpdateSupplierResponse from a JSON string""" + return cls.from_dict(json.loads(json_str)) - timeout_in_minutes: Annotated[ - OptionalNullable[int], pydantic.Field(alias="timeoutInMinutes") - ] = UNSET - r"""Number of minutes the push operation must complete within before it times out.""" + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - timeout_in_seconds: Annotated[ - OptionalNullable[int], - pydantic.Field( - deprecated="warning: ** DEPRECATED ** - This will be removed in a future release, please migrate away from it as soon as possible.", - alias="timeoutInSeconds", - ), - ] = UNSET - r"""Number of seconds the push operation must complete within before it times out.""" + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - validation: Optional[Validation] = None - r"""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.""" + * `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( - [ - "changes", - "completedOnUtc", - "data", - "dataType", - "errorMessage", - "timeoutInMinutes", - "timeoutInSeconds", - "validation", - ] + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, ) - nullable_fields = set( - ["changes", "data", "errorMessage", "timeoutInMinutes", "timeoutInSeconds"] - ) - serialized = handler(self) - m = {} + # 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() + # override the default output from pydantic by calling `to_dict()` of data + if self.data: + _dict['data'] = self.data.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of UpdateSupplierResponse 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"), + "data": UpdateSupplierResponseAllOfData.from_dict(obj["data"]) if obj.get("data") is not None else None + }) + return _obj - 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: - UpdateSupplierResponseAccountingSupplier.model_rebuild() -except NameError: - pass -try: - UpdateSupplierResponse.model_rebuild() -except NameError: - pass +class UpdateSupplierResponseTypedDict(TypedDict): + """TypedDict variant of UpdateSupplierResponse, for dict-literal request/response inputs.""" + changes: NotRequired[Optional[List[PushOperationChangeTypedDict]]] + data_type: NotRequired[Optional[DataType]] + 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] + data: NotRequired[Optional[UpdateSupplierResponseAllOfData]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/validation.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/validation.py index 390342716..99418c46d 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/validation.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/validation.py @@ -1,54 +1,122 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from .validationitem import ValidationItem, ValidationItemTypedDict -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -from pydantic import model_serializer -from typing import List -from typing_extensions import NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class ValidationTypedDict(TypedDict): - r"""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.""" + The version of the OpenAPI document: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) - errors: NotRequired[Nullable[List[ValidationItemTypedDict]]] - warnings: NotRequired[Nullable[List[ValidationItemTypedDict]]] + Do not edit the class manually. +""" # noqa: E501 -class Validation(BaseModel): - r"""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.""" +from __future__ import annotations +import pprint +import re # noqa: F401 +import json - errors: OptionalNullable[List[ValidationItem]] = UNSET +from pydantic import BaseModel, ConfigDict, model_serializer +from typing import Any, ClassVar, Dict, List, Optional +from codat_sync_for_expenses.models.shared.validationitem import ValidationItem, ValidationItemTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict - warnings: OptionalNullable[List[ValidationItem]] = UNSET +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL +class Validation(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 when pushing data into the platform. If a push has failed because of validation errors, they will be detailed here. + """ # noqa: E501 + errors: OptionalNullable[List[ValidationItem]] = UNSET + warnings: OptionalNullable[List[ValidationItem]] = 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 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-expenses/src/codat_sync_for_expenses/models/shared/validationitem.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/validationitem.py index a679bbc08..a818a04ee 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/validationitem.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/validationitem.py @@ -1,66 +1,124 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +# coding: utf-8 -from __future__ import annotations -from codat_sync_for_expenses.types import ( - BaseModel, - Nullable, - OptionalNullable, - UNSET, - UNSET_SENTINEL, -) -import pydantic -from pydantic import model_serializer -from typing_extensions import Annotated, NotRequired, TypedDict +""" + Expenses + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | -class ValidationItemTypedDict(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: prealpha + Contact: expenses@codat.io + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -class ValidationItem(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 - validator_name: Annotated[ - OptionalNullable[str], pydantic.Field(alias="validatorName") - ] = UNSET - r"""Name of validator.""" +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_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL +class ValidationItem(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: - ValidationItem.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) + } + """ + ValidationItem + """ # 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") + 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-expenses/src/codat_sync_for_expenses/models/shared/validfor.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/validfor.py index 5141d7a42..d736a08a6 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/validfor.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/validfor.py @@ -1,14 +1,14 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - from __future__ import annotations + from enum import Enum class ValidFor(str, Enum): - EXPENSE_TRANSACTIONS_PAYMENT = "expense-transactions.Payment" - EXPENSE_TRANSACTIONS_REFUND = "expense-transactions.Refund" - EXPENSE_TRANSACTIONS_REWARD = "expense-transactions.Reward" - EXPENSE_TRANSACTIONS_CHARGEBACK = "expense-transactions.Chargeback" - REIMBURSABLE_EXPENSE_TRANSACTIONS = "reimbursable-expense-transactions" - TRANSFER_TRANSACTIONS = "transfer-transactions" - ADJUSTMENT_TRANSACTIONS = "adjustment-transactions" + """Top-level OAS enum schema (components/schemas/validFor).""" + EXPENSE_TRANSACTIONS_PAYMENT = 'expense-transactions.Payment' + EXPENSE_TRANSACTIONS_REFUND = 'expense-transactions.Refund' + EXPENSE_TRANSACTIONS_REWARD = 'expense-transactions.Reward' + EXPENSE_TRANSACTIONS_CHARGEBACK = 'expense-transactions.Chargeback' + REIMBURSABLE_EXPENSE_TRANSACTIONS = 'reimbursable-expense-transactions' + TRANSFER_TRANSACTIONS = 'transfer-transactions' + ADJUSTMENT_TRANSACTIONS = 'adjustment-transactions' diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/validtransactiontypes.py b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/validtransactiontypes.py index 3751f5020..602df8281 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/models/shared/validtransactiontypes.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/shared/validtransactiontypes.py @@ -1,11 +1,11 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - from __future__ import annotations + from enum import Enum class ValidTransactionTypes(str, Enum): - PAYMENT = "Payment" - REFUND = "Refund" - REWARD = "Reward" - CHARGEBACK = "Chargeback" + """Top-level OAS enum schema (components/schemas/validTransactionTypes).""" + PAYMENT = 'Payment' + REFUND = 'Refund' + REWARD = 'Reward' + CHARGEBACK = 'Chargeback' diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/source_type.py b/sync-for-expenses/src/codat_sync_for_expenses/models/source_type.py new file mode 100644 index 000000000..f78ddf03d --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/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-expenses/src/codat_sync_for_expenses/models/sync_complete_webhook.py b/sync-for-expenses/src/codat_sync_for_expenses/models/sync_complete_webhook.py new file mode 100644 index 000000000..b602f4281 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/sync_complete_webhook.py @@ -0,0 +1,124 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.models.sync_complete_webhook_data import SyncCompleteWebhookData, SyncCompleteWebhookDataTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class SyncCompleteWebhook(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} + """ + Webhook request body used to notify that a sync has completed. + """ # noqa: E501 + client_id: Optional[str] = Field(default=None, description="Unique identifier for your client in Codat.", alias="ClientId") + client_name: Optional[str] = Field(default=None, description="Name of your client in Codat.", alias="ClientName") + company_id: Optional[str] = Field(default=None, description="Unique identifier for your SMB in Codat.", alias="CompanyId") + rule_id: Optional[str] = Field(default=None, description="Unique identifier for the rule.", alias="RuleId") + rule_type: Optional[str] = Field(default=None, description="The type of rule.", alias="RuleType") + alert_id: Optional[str] = Field(default=None, description="Unique identifier of the webhook event.", alias="AlertId") + message: Optional[str] = Field(default=None, description="A human-readable message about the webhook.", alias="Message") + data: Optional[SyncCompleteWebhookData] = Field(default=None, alias="Data") + __properties: ClassVar[List[str]] = ["ClientId", "ClientName", "CompanyId", "RuleId", "RuleType", "AlertId", "Message", "Data"] + + 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 SyncCompleteWebhook 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 data + if self.data: + _dict['Data'] = self.data.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of SyncCompleteWebhook from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "ClientId": obj.get("ClientId"), + "ClientName": obj.get("ClientName"), + "CompanyId": obj.get("CompanyId"), + "RuleId": obj.get("RuleId"), + "RuleType": obj.get("RuleType"), + "AlertId": obj.get("AlertId"), + "Message": obj.get("Message"), + "Data": SyncCompleteWebhookData.from_dict(obj["Data"]) if obj.get("Data") is not None else None + }) + return _obj + + + + + +class SyncCompleteWebhookTypedDict(TypedDict): + """TypedDict variant of SyncCompleteWebhook, for dict-literal request/response inputs.""" + client_id: NotRequired[Optional[str]] + client_name: NotRequired[Optional[str]] + company_id: NotRequired[Optional[str]] + rule_id: NotRequired[Optional[str]] + rule_type: NotRequired[Optional[str]] + alert_id: NotRequired[Optional[str]] + message: NotRequired[Optional[str]] + data: NotRequired[Optional[SyncCompleteWebhookDataTypedDict]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/sync_complete_webhook_data.py b/sync-for-expenses/src/codat_sync_for_expenses/models/sync_complete_webhook_data.py new file mode 100644 index 000000000..5874670cd --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/sync_complete_webhook_data.py @@ -0,0 +1,102 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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 SyncCompleteWebhookData(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} + """ + SyncCompleteWebhookData + """ # noqa: E501 + sync_id: Optional[str] = Field(default=None, description="Unique identifier for the failed sync.", alias="syncId") + sync_type: Optional[str] = Field(default=None, description="The type of sync being performed.", alias="syncType") + __properties: ClassVar[List[str]] = ["syncId", "syncType"] + + 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 SyncCompleteWebhookData 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 SyncCompleteWebhookData from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "syncId": obj.get("syncId"), + "syncType": obj.get("syncType") + }) + return _obj + + + + + +class SyncCompleteWebhookDataTypedDict(TypedDict): + """TypedDict variant of SyncCompleteWebhookData, for dict-literal request/response inputs.""" + sync_id: NotRequired[Optional[str]] + sync_type: NotRequired[Optional[str]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/sync_failed_webhook.py b/sync-for-expenses/src/codat_sync_for_expenses/models/sync_failed_webhook.py new file mode 100644 index 000000000..2bbea44a2 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/sync_failed_webhook.py @@ -0,0 +1,124 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.models.sync_failed_webhook_data import SyncFailedWebhookData, SyncFailedWebhookDataTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class SyncFailedWebhook(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} + """ + Webhook request body used to notify that a sync has failed. + """ # noqa: E501 + client_id: Optional[str] = Field(default=None, description="Unique identifier for your client in Codat.", alias="ClientId") + client_name: Optional[str] = Field(default=None, description="Name of your client in Codat.", alias="ClientName") + company_id: Optional[str] = Field(default=None, description="Unique identifier for your SMB in Codat.", alias="CompanyId") + rule_id: Optional[str] = Field(default=None, description="Unique identifier for the rule.", alias="RuleId") + rule_type: Optional[str] = Field(default=None, description="The type of rule.", alias="RuleType") + alert_id: Optional[str] = Field(default=None, description="Unique identifier of the webhook event.", alias="AlertId") + message: Optional[str] = Field(default=None, description="A human-readable message about the webhook.", alias="Message") + data: Optional[SyncFailedWebhookData] = Field(default=None, alias="Data") + __properties: ClassVar[List[str]] = ["ClientId", "ClientName", "CompanyId", "RuleId", "RuleType", "AlertId", "Message", "Data"] + + 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 SyncFailedWebhook 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 data + if self.data: + _dict['Data'] = self.data.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of SyncFailedWebhook from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "ClientId": obj.get("ClientId"), + "ClientName": obj.get("ClientName"), + "CompanyId": obj.get("CompanyId"), + "RuleId": obj.get("RuleId"), + "RuleType": obj.get("RuleType"), + "AlertId": obj.get("AlertId"), + "Message": obj.get("Message"), + "Data": SyncFailedWebhookData.from_dict(obj["Data"]) if obj.get("Data") is not None else None + }) + return _obj + + + + + +class SyncFailedWebhookTypedDict(TypedDict): + """TypedDict variant of SyncFailedWebhook, for dict-literal request/response inputs.""" + client_id: NotRequired[Optional[str]] + client_name: NotRequired[Optional[str]] + company_id: NotRequired[Optional[str]] + rule_id: NotRequired[Optional[str]] + rule_type: NotRequired[Optional[str]] + alert_id: NotRequired[Optional[str]] + message: NotRequired[Optional[str]] + data: NotRequired[Optional[SyncFailedWebhookDataTypedDict]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/sync_failed_webhook_data.py b/sync-for-expenses/src/codat_sync_for_expenses/models/sync_failed_webhook_data.py new file mode 100644 index 000000000..c0f810714 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/sync_failed_webhook_data.py @@ -0,0 +1,105 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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 SyncFailedWebhookData(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} + """ + SyncFailedWebhookData + """ # noqa: E501 + sync_id: Optional[str] = Field(default=None, description="Unique identifier for the failed sync.", alias="syncId") + sync_type: Optional[str] = Field(default=None, description="The type of sync being performed.", alias="syncType") + failure_stage: Optional[str] = Field(default=None, description="The stage of the job the sync failed.", alias="FailureStage") + __properties: ClassVar[List[str]] = ["syncId", "syncType", "FailureStage"] + + 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 SyncFailedWebhookData 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 SyncFailedWebhookData from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "syncId": obj.get("syncId"), + "syncType": obj.get("syncType"), + "FailureStage": obj.get("FailureStage") + }) + return _obj + + + + + +class SyncFailedWebhookDataTypedDict(TypedDict): + """TypedDict variant of SyncFailedWebhookData, for dict-literal request/response inputs.""" + sync_id: NotRequired[Optional[str]] + sync_type: NotRequired[Optional[str]] + failure_stage: NotRequired[Optional[str]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/sync_initiated.py b/sync-for-expenses/src/codat_sync_for_expenses/models/sync_initiated.py new file mode 100644 index 000000000..caf37efe0 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/sync_initiated.py @@ -0,0 +1,113 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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 SyncInitiated(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} + """ + SyncInitiated + """ # noqa: E501 + sync_id: Optional[str] = Field(default=None, description="Unique identifier for the sync initiated.", alias="syncId") + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["syncId"] + + 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 SyncInitiated 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 SyncInitiated from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "syncId": obj.get("syncId") + }) + # 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 SyncInitiatedTypedDict(TypedDict): + """TypedDict variant of SyncInitiated, for dict-literal request/response inputs.""" + sync_id: NotRequired[Optional[str]] + additional_properties: NotRequired[Dict[str, Any]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/tracking_ref_adjustment_transaction_data_type.py b/sync-for-expenses/src/codat_sync_for_expenses/models/tracking_ref_adjustment_transaction_data_type.py new file mode 100644 index 000000000..42fce1adf --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/tracking_ref_adjustment_transaction_data_type.py @@ -0,0 +1,10 @@ +from __future__ import annotations + +from enum import Enum + + +class TrackingRefAdjustmentTransactionDataType(str, Enum): + """TrackingRefAdjustmentTransactionDataType enum (lifted from inline OAS enum).""" + TRACKING_CATEGORIES = 'trackingCategories' + CUSTOMERS = 'customers' + SUPPLIERS = 'suppliers' diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/tracking_ref_data_type.py b/sync-for-expenses/src/codat_sync_for_expenses/models/tracking_ref_data_type.py new file mode 100644 index 000000000..134728536 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/tracking_ref_data_type.py @@ -0,0 +1,9 @@ +from __future__ import annotations + +from enum import Enum + + +class TrackingRefDataType(str, Enum): + """TrackingRefDataType enum (lifted from inline OAS enum).""" + TRACKING_CATEGORIES = 'trackingCategories' + CUSTOMERS = 'customers' diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/transaction.py b/sync-for-expenses/src/codat_sync_for_expenses/models/transaction.py new file mode 100644 index 000000000..ba9128f27 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/transaction.py @@ -0,0 +1,122 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.models.expenses_sync_webhook_status import ExpensesSyncWebhookStatus +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_expenses.models._compat.transaction import TransactionDefinitionsStatus +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL +class Transaction(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'errorMessage', 'error_message'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + Transaction + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Unique identifier of the transaction.") + status: Optional[TransactionDefinitionsStatus] = Field(default=None, description="Status of transaction.") + error_message: OptionalNullable[str] = Field(default=UNSET, description="Error message for failed transaction.", alias="errorMessage") + __properties: ClassVar[List[str]] = ["id", "status", "errorMessage"] + + @field_validator('status') + def status_validate_enum(cls, value): + """Validates the enum""" + if value is None: + return value + + if value not in set(['Unknown', 'PushError', 'Completed', 'Failed', 'Pending']): + raise ValueError("must be one of enum values ('Unknown', 'PushError', 'Completed', 'Failed', 'Pending')") + 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 Transaction 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 Transaction 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"), + "status": obj.get("status"), + "errorMessage": obj.get("errorMessage") + }) + return _obj + + + + + +class TransactionTypedDict(TypedDict): + """TypedDict variant of Transaction, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + status: NotRequired[Optional[TransactionDefinitionsStatus]] + error_message: NotRequired[Optional[str]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/transfer_transaction_request_from.py b/sync-for-expenses/src/codat_sync_for_expenses/models/transfer_transaction_request_from.py new file mode 100644 index 000000000..95b8d112a --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/transfer_transaction_request_from.py @@ -0,0 +1,108 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.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, Union +from codat_sync_for_expenses.models.account_reference import AccountReference, AccountReferenceTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class TransferTransactionRequestFrom(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} + """ + TransferTransactionRequestFrom + """ # noqa: E501 + account_ref: AccountReference = Field(alias="accountRef") + amount: Annotated[Decimal, BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(description="Amount that has been transferred from the account in the native currency of the account.") + __properties: ClassVar[List[str]] = ["accountRef", "amount"] + + 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 TransferTransactionRequestFrom 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 TransferTransactionRequestFrom from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "accountRef": AccountReference.from_dict(obj["accountRef"]) if obj.get("accountRef") is not None else None, + "amount": obj.get("amount") + }) + return _obj + + + + + +class TransferTransactionRequestFromTypedDict(TypedDict): + """TypedDict variant of TransferTransactionRequestFrom, for dict-literal request/response inputs.""" + account_ref: NotRequired[AccountReferenceTypedDict] + amount: NotRequired[Decimal] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/transfer_transaction_request_to.py b/sync-for-expenses/src/codat_sync_for_expenses/models/transfer_transaction_request_to.py new file mode 100644 index 000000000..6ab4d6933 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/transfer_transaction_request_to.py @@ -0,0 +1,108 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.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, Union +from codat_sync_for_expenses.models.account_reference1 import AccountReference1, AccountReference1TypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class TransferTransactionRequestTo(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} + """ + TransferTransactionRequestTo + """ # noqa: E501 + account_ref: AccountReference1 = Field(alias="accountRef") + amount: Annotated[Decimal, BeforeValidator(validate_decimal), PlainSerializer(serialize_decimal(False))] = Field(description="Amount that has been transferred to the account in the native currency of the account.") + __properties: ClassVar[List[str]] = ["accountRef", "amount"] + + 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 TransferTransactionRequestTo 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 TransferTransactionRequestTo from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "accountRef": AccountReference1.from_dict(obj["accountRef"]) if obj.get("accountRef") is not None else None, + "amount": obj.get("amount") + }) + return _obj + + + + + +class TransferTransactionRequestToTypedDict(TypedDict): + """TypedDict variant of TransferTransactionRequestTo, for dict-literal request/response inputs.""" + account_ref: NotRequired[AccountReference1TypedDict] + amount: NotRequired[Decimal] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/type.py b/sync-for-expenses/src/codat_sync_for_expenses/models/type.py new file mode 100644 index 000000000..3f518004c --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/type.py @@ -0,0 +1,12 @@ +from __future__ import annotations + +from enum import Enum + + +class Type(str, Enum): + """Type enum (lifted from inline OAS enum).""" + FAX = 'Fax' + LANDLINE = 'Landline' + MOBILE = 'Mobile' + PRIMARY = 'Primary' + UNKNOWN = 'Unknown' diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/update_connection.py b/sync-for-expenses/src/codat_sync_for_expenses/models/update_connection.py new file mode 100644 index 000000000..d1d7ac4b2 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/update_connection.py @@ -0,0 +1,114 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.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-expenses/src/codat_sync_for_expenses/models/update_customer_response_all_of_data.py b/sync-for-expenses/src/codat_sync_for_expenses/models/update_customer_response_all_of_data.py new file mode 100644 index 000000000..5b5bf5165 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/update_customer_response_all_of_data.py @@ -0,0 +1,166 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.models.shared.contact import Contact, ContactTypedDict +from codat_sync_for_expenses.models.shared.customerstatus import CustomerStatus +from codat_sync_for_expenses.models.shared.items import Items, ItemsTypedDict +from codat_sync_for_expenses.models.shared.metadata import Metadata, MetadataTypedDict +from codat_sync_for_expenses.models.shared.supplementaldata import SupplementalData, SupplementalDataTypedDict +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class UpdateCustomerResponseAllOfData(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} + """ + UpdateCustomerResponseAllOfData + """ # noqa: E501 + id: Optional[str] = Field(default=None, description="Identifier for the customer, unique to the company in the accounting software.") + customer_name: Optional[str] = Field(default=None, description="Name of the customer as recorded in the accounting system, typically the company name.", alias="customerName") + contact_name: Optional[str] = Field(default=None, description="Name of the main contact for the identified customer.", alias="contactName") + email_address: Optional[str] = Field(default=None, description="Email address the customer can be contacted by.", alias="emailAddress") + default_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.", alias="defaultCurrency") + phone: Optional[str] = Field(default=None, description="Phone number the customer can be contacted by.") + addresses: Optional[List[Items]] = Field(default=None, description="An array of Addresses.") + contacts: Optional[List[Contact]] = Field(default=None, description="An array of Contacts.") + registration_number: Optional[str] = Field(default=None, description="Company number. In the UK, this is typically the Companies House company registration number.", alias="registrationNumber") + tax_number: Optional[str] = Field(default=None, description="Company tax number.", alias="taxNumber") + status: CustomerStatus = Field(description="Current state of the customer.") + metadata: Optional[Metadata] = None + supplemental_data: Optional[SupplementalData] = Field(default=None, alias="supplementalData") + modified_date: Optional[str] = Field(default=None, description="The date when the record was last fetched from the accounting software, commerce software, or open banking provider and updated in Codat’s data cache. Use it to identify and retrieve records that have changed since your last fetch. For example, filtering `modifiedDate` to today will provide new records updated in Codat today. This date is populated for all data types except for attachments, balance sheets, company information, and profit & loss reports ([read more](https://docs.codat.io/using-the-api/modified-dates#modified-date)). In Codat's data model, dates and times are represented using the ISO 8601 standard.", alias="modifiedDate") + 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", "customerName", "contactName", "emailAddress", "defaultCurrency", "phone", "addresses", "contacts", "registrationNumber", "taxNumber", "status", "metadata", "supplementalData", "modifiedDate", "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 UpdateCustomerResponseAllOfData 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 + # override the default output from pydantic by calling `to_dict()` of each item in contacts (list) + _items = [] + if self.contacts: + for _item_contacts in self.contacts: + if _item_contacts: + _items.append(_item_contacts.to_dict()) + _dict['contacts'] = _items + # override the default output from pydantic by calling `to_dict()` of metadata + if self.metadata: + _dict['metadata'] = self.metadata.to_dict() + # override the default output from pydantic by calling `to_dict()` of supplemental_data + if self.supplemental_data: + _dict['supplementalData'] = self.supplemental_data.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of UpdateCustomerResponseAllOfData 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"), + "customerName": obj.get("customerName"), + "contactName": obj.get("contactName"), + "emailAddress": obj.get("emailAddress"), + "defaultCurrency": obj.get("defaultCurrency"), + "phone": obj.get("phone"), + "addresses": [Items.from_dict(_item) for _item in obj["addresses"]] if obj.get("addresses") is not None else None, + "contacts": [Contact.from_dict(_item) for _item in obj["contacts"]] if obj.get("contacts") is not None else None, + "registrationNumber": obj.get("registrationNumber"), + "taxNumber": obj.get("taxNumber"), + "status": obj.get("status"), + "metadata": Metadata.from_dict(obj["metadata"]) if obj.get("metadata") is not None else None, + "supplementalData": SupplementalData.from_dict(obj["supplementalData"]) if obj.get("supplementalData") is not None else None, + "modifiedDate": obj.get("modifiedDate"), + "sourceModifiedDate": obj.get("sourceModifiedDate") + }) + return _obj + + + + + +class UpdateCustomerResponseAllOfDataTypedDict(TypedDict): + """TypedDict variant of UpdateCustomerResponseAllOfData, for dict-literal request/response inputs.""" + id: NotRequired[Optional[str]] + customer_name: NotRequired[Optional[str]] + contact_name: NotRequired[Optional[str]] + email_address: NotRequired[Optional[str]] + default_currency: NotRequired[Optional[str]] + phone: NotRequired[Optional[str]] + addresses: NotRequired[Optional[List[ItemsTypedDict]]] + contacts: NotRequired[Optional[List[ContactTypedDict]]] + registration_number: NotRequired[Optional[str]] + tax_number: NotRequired[Optional[str]] + status: NotRequired[CustomerStatus] + metadata: NotRequired[Optional[MetadataTypedDict]] + supplemental_data: NotRequired[Optional[SupplementalDataTypedDict]] + modified_date: NotRequired[Optional[str]] + source_modified_date: NotRequired[Optional[str]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/update_expense_request_type.py b/sync-for-expenses/src/codat_sync_for_expenses/models/update_expense_request_type.py new file mode 100644 index 000000000..60bca02e9 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/update_expense_request_type.py @@ -0,0 +1,11 @@ +from __future__ import annotations + +from enum import Enum + + +class UpdateExpenseRequestType(str, Enum): + """UpdateExpenseRequestType enum (lifted from inline OAS enum).""" + PAYMENT = 'Payment' + REFUND = 'Refund' + REWARD = 'Reward' + CHARGEBACK = 'Chargeback' diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/update_supplier_response_all_of_data.py b/sync-for-expenses/src/codat_sync_for_expenses/models/update_supplier_response_all_of_data.py new file mode 100644 index 000000000..466875401 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/update_supplier_response_all_of_data.py @@ -0,0 +1,155 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.models.shared.items import Items, ItemsTypedDict +from codat_sync_for_expenses.models.shared.metadata import Metadata, MetadataTypedDict +from codat_sync_for_expenses.models.shared.supplementaldata import SupplementalData, SupplementalDataTypedDict +from codat_sync_for_expenses.models.shared.supplierstatus import SupplierStatus +from typing import Optional, Set +from typing_extensions import Self, NotRequired, TypedDict + +class UpdateSupplierResponseAllOfData(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} + """ + UpdateSupplierResponseAllOfData + """ # 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: Optional[str] = Field(default=None, description="Name of the main contact for the supplier.", alias="contactName") + email_address: Optional[str] = Field(default=None, description="Email address that the supplier may be contacted on.", alias="emailAddress") + phone: Optional[str] = Field(default=None, description="Phone number that the supplier may be contacted on.") + addresses: Optional[List[Items]] = Field(default=None, description="An array of Addresses.") + registration_number: Optional[str] = Field(default=None, description="Company number of the supplier. In the UK, this is typically the company registration number issued by Companies House.", alias="registrationNumber") + tax_number: Optional[str] = Field(default=None, description="Supplier's company tax number.", alias="taxNumber") + status: SupplierStatus + default_currency: Optional[str] = Field(default=None, description="Default currency the supplier's transactional data is recorded in.", alias="defaultCurrency") + metadata: Optional[Metadata] = None + supplemental_data: Optional[SupplementalData] = Field(default=None, alias="supplementalData") + modified_date: Optional[str] = Field(default=None, description="The date when the record was last fetched from the accounting software, commerce software, or open banking provider and updated in Codat’s data cache. Use it to identify and retrieve records that have changed since your last fetch. For example, filtering `modifiedDate` to today will provide new records updated in Codat today. This date is populated for all data types except for attachments, balance sheets, company information, and profit & loss reports ([read more](https://docs.codat.io/using-the-api/modified-dates#modified-date)). In Codat's data model, dates and times are represented using the ISO 8601 standard.", alias="modifiedDate") + 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", "registrationNumber", "taxNumber", "status", "defaultCurrency", "metadata", "supplementalData", "modifiedDate", "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 UpdateSupplierResponseAllOfData 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 + # override the default output from pydantic by calling `to_dict()` of metadata + if self.metadata: + _dict['metadata'] = self.metadata.to_dict() + # override the default output from pydantic by calling `to_dict()` of supplemental_data + if self.supplemental_data: + _dict['supplementalData'] = self.supplemental_data.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of UpdateSupplierResponseAllOfData 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": [Items.from_dict(_item) for _item in obj["addresses"]] if obj.get("addresses") is not None else None, + "registrationNumber": obj.get("registrationNumber"), + "taxNumber": obj.get("taxNumber"), + "status": obj.get("status"), + "defaultCurrency": obj.get("defaultCurrency"), + "metadata": Metadata.from_dict(obj["metadata"]) if obj.get("metadata") is not None else None, + "supplementalData": SupplementalData.from_dict(obj["supplementalData"]) if obj.get("supplementalData") is not None else None, + "modifiedDate": obj.get("modifiedDate"), + "sourceModifiedDate": obj.get("sourceModifiedDate") + }) + return _obj + + + + + +class UpdateSupplierResponseAllOfDataTypedDict(TypedDict): + """TypedDict variant of UpdateSupplierResponseAllOfData, 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[ItemsTypedDict]]] + registration_number: NotRequired[Optional[str]] + tax_number: NotRequired[Optional[str]] + status: SupplierStatus + default_currency: NotRequired[Optional[str]] + metadata: NotRequired[Optional[MetadataTypedDict]] + supplemental_data: NotRequired[Optional[SupplementalDataTypedDict]] + modified_date: NotRequired[Optional[str]] + source_modified_date: NotRequired[Optional[str]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/valid_data_type_links.py b/sync-for-expenses/src/codat_sync_for_expenses/models/valid_data_type_links.py new file mode 100644 index 000000000..a6ec611f7 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/valid_data_type_links.py @@ -0,0 +1,107 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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 + +from codat_sync_for_expenses.types import OptionalNullable, UNSET, UNSET_SENTINEL +class ValidDataTypeLinks(BaseModel): + + @model_serializer(mode="wrap") + def _serialize_drop_none(self, handler): + serialized = handler(self) + _nullable = {'links', 'property'} + return { + k: v for k, v in serialized.items() + if v != UNSET_SENTINEL and (v is not None or k in _nullable) + } + """ + When querying Codat's data model, some data types return `validDatatypeLinks` metadata in the JSON response. This indicates where that object can be used as a reference—a _valid link_—when creating or updating other data. For example, `validDatatypeLinks` might indicate the following references: - Which tax rates are valid to use on the line item of a bill. - Which items can be used when creating an invoice. You can use `validDatatypeLinks` to present your SMB customers with only valid choices when selecting objects from a list, for example. ## `validDatatypeLinks` example The following example uses the `Accounting.Accounts` data type. It shows that, on the linked integration, this account is valid as the account on a payment or bill payment; and as the account referenced on the line item of a direct income or direct cost. Because there is no valid link to Invoices or Bills, using this account on those data types will result in an error. ```json validDatatypeLinks for an account { \"id\": \"bd9e85e0-0478-433d-ae9f-0b3c4f04bfe4\", \"nominalCode\": \"090\", \"name\": \"Business Bank Account\", #... \"validDatatypeLinks\": [ { \"property\": \"Id\", \"links\": [ \"Payment.AccountRef.Id\", \"BillPayment.AccountRef.Id\", \"DirectIncome.LineItems.AccountRef.Id\", \"DirectCost.LineItems.AccountRef.Id\" ] } ] } ``` ## Support for `validDatatypeLinks` Codat currently supports `validDatatypeLinks` for some data types on our Xero, QuickBooks Online, QuickBooks Desktop, Exact (NL), and Sage Business Cloud integrations. If you'd like us to extend support to more data types or integrations, suggest or vote for this on our Product Roadmap. + """ # noqa: E501 + property: OptionalNullable[str] = Field(default=UNSET, description="The property from the account that can be linked.", alias="property") + links: OptionalNullable[List[str]] = Field(default=UNSET, description="Supported `dataTypes` that the record can be linked to.") + __properties: ClassVar[List[str]] = ["property", "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 ValidDataTypeLinks 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 ValidDataTypeLinks from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "property": obj.get("property"), + "links": obj.get("links") + }) + return _obj + + + + + +class ValidDataTypeLinksTypedDict(TypedDict): + """TypedDict variant of ValidDataTypeLinks, for dict-literal request/response inputs.""" + property: NotRequired[Optional[str]] + links: NotRequired[Optional[List[str]]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/models/weblink.py b/sync-for-expenses/src/codat_sync_for_expenses/models/weblink.py new file mode 100644 index 000000000..3cf29b645 --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/models/weblink.py @@ -0,0 +1,114 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.models.company_information_type import CompanyInformationType +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_expenses.models._compat.companyinformation import CompanyInformationSchemasType +class Weblink(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} + """ + Weblink associated with the company. + """ # noqa: E501 + type: Optional[CompanyInformationSchemasType] = Field(default=None, description="The type of the weblink.") + url: Optional[str] = Field(default=None, description="The full URL for the weblink.") + __properties: ClassVar[List[str]] = ["type", "url"] + + @field_validator('type') + def type_validate_enum(cls, value): + """Validates the enum""" + if value is None: + return value + + if value not in set(['Website', 'Social', 'Unknown']): + raise ValueError("must be one of enum values ('Website', 'Social', '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 Weblink 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 Weblink 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"), + "url": obj.get("url") + }) + return _obj + + + + + +class WeblinkTypedDict(TypedDict): + """TypedDict variant of Weblink, for dict-literal request/response inputs.""" + type: NotRequired[Optional[CompanyInformationSchemasType]] + url: NotRequired[Optional[str]] diff --git a/sync-for-expenses/src/codat_sync_for_expenses/push_operations.py b/sync-for-expenses/src/codat_sync_for_expenses/push_operations.py index 236ddb112..988954aa6 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/push_operations.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/push_operations.py @@ -1,407 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.push_operations — re-export of the push_operations method group.""" -from .basesdk import BaseSDK -from codat_sync_for_expenses import utils -from codat_sync_for_expenses._hooks import HookContext -from codat_sync_for_expenses.models import errors, operations, shared -from codat_sync_for_expenses.types import BaseModel, OptionalNullable, UNSET -from codat_sync_for_expenses.utils.unmarshal_json_response import ( - unmarshal_json_response, -) -from typing import Any, Mapping, Optional, Union, cast - - -class PushOperations(BaseSDK): - r"""View historic push operations.""" - - def get( - self, - *, - request: Union[ - operations.GetPushOperationRequest, - operations.GetPushOperationRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.PushOperation: - r"""Get push operation - - Retrieve push operation. - - :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.GetPushOperationRequest) - request = cast(operations.GetPushOperationRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/push/{pushOperationKey}", - 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-push-operation", - 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.PushOperation, 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.GetPushOperationRequest, - operations.GetPushOperationRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.PushOperation: - r"""Get push operation - - Retrieve push operation. - - :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.GetPushOperationRequest) - request = cast(operations.GetPushOperationRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/push/{pushOperationKey}", - 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-push-operation", - 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.PushOperation, 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 list( - self, - *, - request: Union[ - operations.ListPushOperationsRequest, - operations.ListPushOperationsRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.PushOperations: - r"""List push operations - - List push operation records. - - :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.ListPushOperationsRequest) - request = cast(operations.ListPushOperationsRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/push", - 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-push-operations", - 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.PushOperations, 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.ListPushOperationsRequest, - operations.ListPushOperationsRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.PushOperations: - r"""List push operations - - List push operation records. - - :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.ListPushOperationsRequest) - request = cast(operations.ListPushOperationsRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/push", - 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-push-operations", - 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.PushOperations, 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_expenses.api.push_operations import PushOperations diff --git a/sync-for-expenses/src/codat_sync_for_expenses/py.typed b/sync-for-expenses/src/codat_sync_for_expenses/py.typed index 3e38f1a92..e69de29bb 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/py.typed +++ b/sync-for-expenses/src/codat_sync_for_expenses/py.typed @@ -1 +0,0 @@ -# Marker file for PEP 561. The package enables type hints. diff --git a/sync-for-expenses/src/codat_sync_for_expenses/reimbursements.py b/sync-for-expenses/src/codat_sync_for_expenses/reimbursements.py index 0b774fd7e..3f7fd8aae 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/reimbursements.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/reimbursements.py @@ -1,503 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.reimbursements — re-export of the reimbursements method group.""" -from .basesdk import BaseSDK -from codat_sync_for_expenses import utils -from codat_sync_for_expenses._hooks import HookContext -from codat_sync_for_expenses.models import errors, operations, shared -from codat_sync_for_expenses.types import BaseModel, OptionalNullable, UNSET -from codat_sync_for_expenses.utils.unmarshal_json_response import ( - unmarshal_json_response, -) -from typing import Any, List, Mapping, Optional, Union, cast - - -class Reimbursements(BaseSDK): - r"""Create and update transactions that represent your customers' repayable spend.""" - - def create( - self, - *, - request: Union[ - operations.CreateReimbursableExpenseTransactionRequest, - operations.CreateReimbursableExpenseTransactionRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.CreateReimbursableExpenseResponse: - r"""Create reimbursable expense transaction - - Use the *Create reimbursable expense* endpoint to submit an employee expense claim in the accounting platform for a given company's connection. - - [Reimbursable expense requests](https://docs.codat.io/sync-for-expenses-api#/schemas/ReimbursableExpenseTransactionRequest) are reflected in the accounting software in the form of **Bills** against an employee (who exists as a supplier in the accounting platform). - - ### Supported Integrations - | Integration | Supported | - |-----------------------|-----------| - | FreeAgent | Yes | - | QuickBooks Desktop | Yes | - | QuickBooks Online | Yes | - | Oracle NetSuite | Yes | - | Zoho Books | Yes | - | Sage Intacct | 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.CreateReimbursableExpenseTransactionRequest - ) - request = cast(operations.CreateReimbursableExpenseTransactionRequest, request) - - req = self._build_request( - method="POST", - path="/companies/{companyId}/sync/expenses/reimbursable-expense-transactions", - 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[List[shared.ReimbursableExpenseTransaction]], - ), - 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-reimbursable-expense-transaction", - 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.CreateReimbursableExpenseResponse, 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.CreateReimbursableExpenseTransactionRequest, - operations.CreateReimbursableExpenseTransactionRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.CreateReimbursableExpenseResponse: - r"""Create reimbursable expense transaction - - Use the *Create reimbursable expense* endpoint to submit an employee expense claim in the accounting platform for a given company's connection. - - [Reimbursable expense requests](https://docs.codat.io/sync-for-expenses-api#/schemas/ReimbursableExpenseTransactionRequest) are reflected in the accounting software in the form of **Bills** against an employee (who exists as a supplier in the accounting platform). - - ### Supported Integrations - | Integration | Supported | - |-----------------------|-----------| - | FreeAgent | Yes | - | QuickBooks Desktop | Yes | - | QuickBooks Online | Yes | - | Oracle NetSuite | Yes | - | Zoho Books | Yes | - | Sage Intacct | 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.CreateReimbursableExpenseTransactionRequest - ) - request = cast(operations.CreateReimbursableExpenseTransactionRequest, request) - - req = self._build_request_async( - method="POST", - path="/companies/{companyId}/sync/expenses/reimbursable-expense-transactions", - 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[List[shared.ReimbursableExpenseTransaction]], - ), - 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-reimbursable-expense-transaction", - 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.CreateReimbursableExpenseResponse, 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.UpdateReimbursableExpenseTransactionRequest, - operations.UpdateReimbursableExpenseTransactionRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.CreateReimbursableExpenseResponse: - r"""Update reimbursable expense transaction - - The *Update reimbursable expense* endpoint updates an existing employee expense claim in the accounting platform for a given company's connection. - - Updating an existing [reimbursable expense transaction](https://docs.codat.io/sync-for-expenses-api#/schemas/UpdateReimbursableExpenseTransactionRequest) will update the existing **bill** against an employee (who exists as a supplier in the accounting software). - - ### Supported Integrations - | Integration | Supported | - |-----------------------|-----------| - | FreeAgent | Yes | - | QuickBooks Online | Yes | - | Oracle NetSuite | 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.UpdateReimbursableExpenseTransactionRequest - ) - request = cast(operations.UpdateReimbursableExpenseTransactionRequest, request) - - req = self._build_request( - method="PUT", - path="/companies/{companyId}/sync/expenses/reimbursable-expense-transactions/{transactionId}", - 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.update_reimbursable_expense_transaction_request - if request is not None - else None, - False, - True, - "json", - Optional[shared.UpdateReimbursableExpenseTransactionRequest], - ), - 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-reimbursable-expense-transaction", - 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.CreateReimbursableExpenseResponse, 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.UpdateReimbursableExpenseTransactionRequest, - operations.UpdateReimbursableExpenseTransactionRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.CreateReimbursableExpenseResponse: - r"""Update reimbursable expense transaction - - The *Update reimbursable expense* endpoint updates an existing employee expense claim in the accounting platform for a given company's connection. - - Updating an existing [reimbursable expense transaction](https://docs.codat.io/sync-for-expenses-api#/schemas/UpdateReimbursableExpenseTransactionRequest) will update the existing **bill** against an employee (who exists as a supplier in the accounting software). - - ### Supported Integrations - | Integration | Supported | - |-----------------------|-----------| - | FreeAgent | Yes | - | QuickBooks Online | Yes | - | Oracle NetSuite | 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.UpdateReimbursableExpenseTransactionRequest - ) - request = cast(operations.UpdateReimbursableExpenseTransactionRequest, request) - - req = self._build_request_async( - method="PUT", - path="/companies/{companyId}/sync/expenses/reimbursable-expense-transactions/{transactionId}", - 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.update_reimbursable_expense_transaction_request - if request is not None - else None, - False, - True, - "json", - Optional[shared.UpdateReimbursableExpenseTransactionRequest], - ), - 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-reimbursable-expense-transaction", - 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.CreateReimbursableExpenseResponse, 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_expenses.api.reimbursements import Reimbursements diff --git a/sync-for-expenses/src/codat_sync_for_expenses/rest.py b/sync-for-expenses/src/codat_sync_for_expenses/rest.py new file mode 100644 index 000000000..1fad2f6af --- /dev/null +++ b/sync-for-expenses/src/codat_sync_for_expenses/rest.py @@ -0,0 +1,258 @@ +# coding: utf-8 + +""" + Expenses + + The API for Codat's Expenses solution. Expenses is an API and a set of supporting tools. It has been built to enable corporate card and expense management platforms to provide high-quality integrations with multiple accounting software through a standardized API. [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). --- ## Endpoints | Endpoints | Description | | :- |:- | | Companies | Create and manage your SMB users' companies. | | Connections | Create new and manage existing data connections for a company. | | Configuration | View and manage mapping configuration and defaults for expense transactions. | | Sync | Monitor the status of data syncs. | | Expenses | Create and update transactions that represent your customers' spend. | | Transfers | Create and update transactions that represent the movement of your customers' money. | | Reimbursements | Create and update transactions that represent your customers' repayable spend. | | Attachments | Attach receipts to a transaction for a complete audit trail. | | Transaction status | Monitor the status of individual transactions in data syncs. | | Manage data | Control and monitor the retrieval of data from an integration. | | Push operations | View historic push operations. | | Accounts | Create accounts and view account schemas. | | Customers | Get, create, and update customers. | | Suppliers | Get, create, and update suppliers. | + + The version of the OpenAPI document: prealpha + Contact: expenses@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_expenses.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-expenses/src/codat_sync_for_expenses/sdk.py b/sync-for-expenses/src/codat_sync_for_expenses/sdk.py index 83328ccee..b1d2e0091 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/sdk.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/sdk.py @@ -1,144 +1,117 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""Top-level composed client for Expenses. -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_expenses import utils -from codat_sync_for_expenses._hooks import SDKHooks -from codat_sync_for_expenses.models import shared -from codat_sync_for_expenses.types import OptionalNullable, UNSET -import httpx -import importlib -import sys -from typing import Callable, Dict, Optional, TYPE_CHECKING, Union, cast -import weakref +Generated by pipeline/postprocess_generated.py — do not edit by hand. +""" -if TYPE_CHECKING: - from codat_sync_for_expenses.accounts import Accounts - from codat_sync_for_expenses.adjustments import Adjustments - from codat_sync_for_expenses.attachments import Attachments - from codat_sync_for_expenses.bank_accounts import BankAccounts - from codat_sync_for_expenses.companies import Companies - from codat_sync_for_expenses.company_info import CompanyInfo - from codat_sync_for_expenses.configuration import Configuration - from codat_sync_for_expenses.connections import Connections - from codat_sync_for_expenses.customers import Customers - from codat_sync_for_expenses.expenses import Expenses - from codat_sync_for_expenses.manage_data import ManageData - from codat_sync_for_expenses.mapping_options import MappingOptions - from codat_sync_for_expenses.push_operations import PushOperations - from codat_sync_for_expenses.reimbursements import Reimbursements - from codat_sync_for_expenses.suppliers import Suppliers - from codat_sync_for_expenses.sync import Sync - from codat_sync_for_expenses.transaction_status import TransactionStatus - from codat_sync_for_expenses.transfers import Transfers - - -class CodatSyncExpenses(BaseSDK): - r"""Expenses: The API for Codat's Expenses solution. +from __future__ import annotations - Expenses is an API and a set of supporting tools. It has been built to - enable corporate card and expense management platforms to provide high-quality - integrations with multiple accounting software through a standardized API. +from typing import TYPE_CHECKING, Any, Callable, Dict, Mapping, Optional, Union - [Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) +from codat_sync_for_expenses.api_client import ApiClient +from codat_sync_for_expenses.configuration import Configuration +from codat_sync_for_expenses._hooks import SDKHooks, attach_hooks_to_api_client +from codat_sync_for_expenses.types import UNSET, OptionalNullable +from codat_sync_for_expenses.utils.retries import RetryConfig - Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). - - --- - - ## Endpoints +if TYPE_CHECKING: + from codat_sync_for_expenses.httpclient import AsyncHttpClient, HttpClient + +from codat_sync_for_expenses.api.companies import Companies +from codat_sync_for_expenses.api.connections import Connections +from codat_sync_for_expenses.api.company_info import CompanyInfo +from codat_sync_for_expenses.api.manage_data import ManageData +from codat_sync_for_expenses.api.mapping_options import MappingOptions +from codat_sync_for_expenses.api.accounts import Accounts +from codat_sync_for_expenses.api.bank_accounts import BankAccounts +from codat_sync_for_expenses.api.customers import Customers +from codat_sync_for_expenses.api.suppliers import Suppliers +from codat_sync_for_expenses.api.push_operations import PushOperations +from codat_sync_for_expenses.api.configuration import Configuration as ConfigurationApi +from codat_sync_for_expenses.api.expenses import Expenses +from codat_sync_for_expenses.api.reimbursements import Reimbursements +from codat_sync_for_expenses.api.transfers import Transfers +from codat_sync_for_expenses.api.adjustments import Adjustments +from codat_sync_for_expenses.api.attachments import Attachments +from codat_sync_for_expenses.api.sync import Sync +from codat_sync_for_expenses.api.transaction_status import TransactionStatus + + +_DEFAULT_TIMEOUT_MS = 5000 + + +class CodatSyncExpenses: + r"""Expenses: The API for Codat's Expenses solution. - | Endpoints | Description | - | :- |:- | - | Companies | Create and manage your SMB users' companies. | - | Connections | Create new and manage existing data connections for a company. | - | Configuration | View and manage mapping configuration and defaults for expense transactions. | - | Sync | Monitor the status of data syncs. | - | Expenses | Create and update transactions that represent your customers' spend. | - | Transfers | Create and update transactions that represent the movement of your customers' money. | - | Reimbursements | Create and update transactions that represent your customers' repayable spend. | - | Attachments | Attach receipts to a transaction for a complete audit trail. | - | Transaction status | Monitor the status of individual transactions in data syncs. | - | Manage data | Control and monitor the retrieval of data from an integration. | - | Push operations | View historic push operations. | - | Accounts | Create accounts and view account schemas. | - | Customers | Get, create, and update customers. | - | Suppliers | Get, create, and update suppliers. | - - """ +Expenses is an API and a set of supporting tools. It has been built to +enable corporate card and expense management platforms to provide high-quality +integrations with multiple accounting software through a standardized API. + +[Explore solution](https://docs.codat.io/sync-for-expenses/overview) | [See our OpenAPI spec](https://github.com/codatio/oas) + +Not seeing the endpoints you're expecting? We've [reorganized our solutions](https://docs.codat.io/updates/230901-new-products), and you may be using a [different version of Expenses](https://docs.codat.io/sync-for-expenses-v1-api#/). + +--- + +## Endpoints + +| Endpoints | Description | +| :- |:- | +| Companies | Create and manage your SMB users' companies. | +| Connections | Create new and manage existing data connections for a company. | +| Configuration | View and manage mapping configuration and defaults for expense transactions. | +| Sync | Monitor the status of data syncs. | +| Expenses | Create and update transactions that represent your customers' spend. | +| Transfers | Create and update transactions that represent the movement of your customers' money. | +| Reimbursements | Create and update transactions that represent your customers' repayable spend. | +| Attachments | Attach receipts to a transaction for a complete audit trail. | +| Transaction status | Monitor the status of individual transactions in data syncs. | +| Manage data | Control and monitor the retrieval of data from an integration. | +| Push operations | View historic push operations. | +| Accounts | Create accounts and view account schemas. | +| Customers | Get, create, and update customers. | +| Suppliers | Get, create, and update suppliers. | +""" companies: "Companies" r"""Create and manage your SMB users' companies.""" connections: "Connections" r"""Create new and manage existing data connections for a company.""" - bank_accounts: "BankAccounts" - r"""Create bank accounts and view create bank account options.""" + company_info: "CompanyInfo" + r"""View the company information of your customers' linked accounting software.""" + manage_data: "ManageData" + r"""Control and monitor the retrieval of data from an integration.""" + mapping_options: "MappingOptions" + r"""Get accounts, trackingCategories and taxRates that can be used in your create and update requests.""" accounts: "Accounts" r"""Create accounts and view create account options.""" + bank_accounts: "BankAccounts" + r"""Create bank accounts and view create bank account options.""" customers: "Customers" r"""Get, create, and update customers.""" suppliers: "Suppliers" r"""Get, create, and update suppliers.""" - manage_data: "ManageData" - r"""Control and monitor the retrieval of data from an integration.""" - company_info: "CompanyInfo" - r"""View the company information of your customers' linked accounting software.""" push_operations: "PushOperations" r"""View historic push operations.""" - adjustments: "Adjustments" - r"""Create transactions that represent your adjustments to your customers' spend.""" - configuration: "Configuration" + configuration: "ConfigurationApi" r"""View and manage mapping configuration and defaults for expense transactions.""" expenses: "Expenses" r"""Create and update transactions that represent your customers' spend.""" - mapping_options: "MappingOptions" - r"""Get accounts, trackingCategories and taxRates that can be used in your create and update requests.""" reimbursements: "Reimbursements" r"""Create and update transactions that represent your customers' repayable spend.""" + transfers: "Transfers" + r"""Create and update transactions that represent the movement of your customers' money.""" + adjustments: "Adjustments" + r"""Create transactions that represent your adjustments to your customers' spend.""" + attachments: "Attachments" + r"""Attach receipts to a transaction for a complete audit trail.""" sync: "Sync" r"""Monitor the status of data syncs.""" transaction_status: "TransactionStatus" r"""Monitor the status of individual transactions in data syncs.""" - attachments: "Attachments" - r"""Attach receipts to a transaction for a complete audit trail.""" - transfers: "Transfers" - r"""Create and update transactions that represent the movement of your customers' money.""" - _sub_sdk_map = { - "companies": ("codat_sync_for_expenses.companies", "Companies"), - "connections": ("codat_sync_for_expenses.connections", "Connections"), - "bank_accounts": ("codat_sync_for_expenses.bank_accounts", "BankAccounts"), - "accounts": ("codat_sync_for_expenses.accounts", "Accounts"), - "customers": ("codat_sync_for_expenses.customers", "Customers"), - "suppliers": ("codat_sync_for_expenses.suppliers", "Suppliers"), - "manage_data": ("codat_sync_for_expenses.manage_data", "ManageData"), - "company_info": ("codat_sync_for_expenses.company_info", "CompanyInfo"), - "push_operations": ( - "codat_sync_for_expenses.push_operations", - "PushOperations", - ), - "adjustments": ("codat_sync_for_expenses.adjustments", "Adjustments"), - "configuration": ("codat_sync_for_expenses.configuration", "Configuration"), - "expenses": ("codat_sync_for_expenses.expenses", "Expenses"), - "mapping_options": ( - "codat_sync_for_expenses.mapping_options", - "MappingOptions", - ), - "reimbursements": ("codat_sync_for_expenses.reimbursements", "Reimbursements"), - "sync": ("codat_sync_for_expenses.sync", "Sync"), - "transaction_status": ( - "codat_sync_for_expenses.transaction_status", - "TransactionStatus", - ), - "attachments": ("codat_sync_for_expenses.attachments", "Attachments"), - "transfers": ("codat_sync_for_expenses.transfers", "Transfers"), - } 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, @@ -146,139 +119,110 @@ 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, - ) - - 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}'" + 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_expenses._httpx_transport import HttpxRestClient + self._api_client.rest_client = HttpxRestClient(client) + try: + from codat_sync_for_expenses._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')], ) - 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_info = CompanyInfo(api_client=self._api_client) + self.manage_data = ManageData(api_client=self._api_client) + self.mapping_options = MappingOptions(api_client=self._api_client) + self.accounts = Accounts(api_client=self._api_client) + self.bank_accounts = BankAccounts(api_client=self._api_client) + self.customers = Customers(api_client=self._api_client) + self.suppliers = Suppliers(api_client=self._api_client) + self.push_operations = PushOperations(api_client=self._api_client) + self.configuration = ConfigurationApi(api_client=self._api_client) + self.expenses = Expenses(api_client=self._api_client) + self.reimbursements = Reimbursements(api_client=self._api_client) + self.transfers = Transfers(api_client=self._api_client) + self.adjustments = Adjustments(api_client=self._api_client) + self.attachments = Attachments(api_client=self._api_client) + self.sync = Sync(api_client=self._api_client) + self.transaction_status = TransactionStatus(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_info, + self.manage_data, + self.mapping_options, + self.accounts, + self.bank_accounts, + self.customers, + self.suppliers, + self.push_operations, + self.configuration, + self.expenses, + self.reimbursements, + self.transfers, + self.adjustments, + self.attachments, + self.sync, + self.transaction_status, + ): + _attach_sdk_defaults(_grp) - def __enter__(self): + def __enter__(self) -> "CodatSyncExpenses": + 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) -> "CodatSyncExpenses": + 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-expenses/src/codat_sync_for_expenses/sdkconfiguration.py b/sync-for-expenses/src/codat_sync_for_expenses/sdkconfiguration.py deleted file mode 100644 index c775d7e3c..000000000 --- a/sync-for-expenses/src/codat_sync_for_expenses/sdkconfiguration.py +++ /dev/null @@ -1,48 +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_expenses.models import shared -from codat_sync_for_expenses.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", -] -"""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-expenses/src/codat_sync_for_expenses/suppliers.py b/sync-for-expenses/src/codat_sync_for_expenses/suppliers.py index e4d2e5578..e60aca74f 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/suppliers.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/suppliers.py @@ -1,965 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.suppliers — re-export of the suppliers method group.""" -from .basesdk import BaseSDK -from codat_sync_for_expenses import utils -from codat_sync_for_expenses._hooks import HookContext -from codat_sync_for_expenses.models import errors, operations, shared -from codat_sync_for_expenses.types import BaseModel, OptionalNullable, UNSET -from codat_sync_for_expenses.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 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.CreateSupplierResponse: - r"""Create supplier - - The *Create supplier* endpoint creates a new [supplier](https://docs.codat.io/sync-for-expenses-api#/schemas/Supplier) for a given company's connection. - - [Suppliers](https://docs.codat.io/sync-for-expenses-api#/schemas/Supplier) are people or organizations that provide something, such as a product or service. - - **Integration-specific behavior** - - Required data may vary by integration. To see what data to post, first call [Get create/update supplier model](https://docs.codat.io/sync-for-expenses-api#/operations/get-create-update-suppliers-model). - - ### Supported Integrations - - | Integration | Supported | - |-------------------------------|-----------| - | Dynamics 365 Business Central | Yes | - | FreeAgent | Yes | - | Oracle NetSuite | Yes | - | QuickBooks Desktop | Yes | - | QuickBooks Online | Yes | - | Sage Intacct | Yes | - | Xero | 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}/push/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 if request is not None else None, - True, - True, - "json", - OptionalNullable[shared.Supplier], - ), - 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, "200", "application/json"): - return unmarshal_json_response(shared.CreateSupplierResponse, 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.CreateSupplierResponse: - r"""Create supplier - - The *Create supplier* endpoint creates a new [supplier](https://docs.codat.io/sync-for-expenses-api#/schemas/Supplier) for a given company's connection. - - [Suppliers](https://docs.codat.io/sync-for-expenses-api#/schemas/Supplier) are people or organizations that provide something, such as a product or service. - - **Integration-specific behavior** - - Required data may vary by integration. To see what data to post, first call [Get create/update supplier model](https://docs.codat.io/sync-for-expenses-api#/operations/get-create-update-suppliers-model). - - ### Supported Integrations - - | Integration | Supported | - |-------------------------------|-----------| - | Dynamics 365 Business Central | Yes | - | FreeAgent | Yes | - | Oracle NetSuite | Yes | - | QuickBooks Desktop | Yes | - | QuickBooks Online | Yes | - | Sage Intacct | Yes | - | Xero | 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}/push/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 if request is not None else None, - True, - True, - "json", - OptionalNullable[shared.Supplier], - ), - 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, "200", "application/json"): - return unmarshal_json_response(shared.CreateSupplierResponse, 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 get( - self, - *, - request: Union[ - operations.GetSupplierRequest, operations.GetSupplierRequestTypedDict - ], - 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"""Get supplier - - The *Get supplier* endpoint returns a single supplier for a given supplierId. - - [Suppliers](https://docs.codat.io/sync-for-expenses-api#/schemas/Supplier) are people or organizations that provide something, such as a product or service. - - Before using this endpoint, you must have [retrieved data for the company](https://docs.codat.io/sync-for-expenses-api#/operations/refresh-all-data-types). - - ### Supported Integrations - - | Integration | Supported | - |-------------------------------|-----------| - | Dynamics 365 Business Central | Yes | - | FreeAgent | Yes | - | Oracle NetSuite | Yes | - | QuickBooks Desktop | Yes | - | QuickBooks Online | Yes | - | Sage Intacct | Yes | - | Xero | 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.GetSupplierRequest) - request = cast(operations.GetSupplierRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/data/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, - 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-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, ["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 get_async( - self, - *, - request: Union[ - operations.GetSupplierRequest, operations.GetSupplierRequestTypedDict - ], - 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"""Get supplier - - The *Get supplier* endpoint returns a single supplier for a given supplierId. - - [Suppliers](https://docs.codat.io/sync-for-expenses-api#/schemas/Supplier) are people or organizations that provide something, such as a product or service. - - Before using this endpoint, you must have [retrieved data for the company](https://docs.codat.io/sync-for-expenses-api#/operations/refresh-all-data-types). - - ### Supported Integrations - - | Integration | Supported | - |-------------------------------|-----------| - | Dynamics 365 Business Central | Yes | - | FreeAgent | Yes | - | Oracle NetSuite | Yes | - | QuickBooks Desktop | Yes | - | QuickBooks Online | Yes | - | Sage Intacct | Yes | - | Xero | 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.GetSupplierRequest) - request = cast(operations.GetSupplierRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/data/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, - 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-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, ["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 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-expenses-api#/schemas/Supplier) for a given company's connection. - - [Suppliers](https://docs.codat.io/sync-for-expenses-api#/schemas/Supplier) are people or organizations that provide something, such as a product or service. - - Before using this endpoint, you must have [retrieved data for the company](https://docs.codat.io/sync-for-expenses-api#/operations/refresh-all-data-types). - - ### Supported Integrations - - | Integration | Supported | - |-------------------------------|-----------| - | Dynamics 365 Business Central | Yes | - | FreeAgent | Yes | - | Oracle NetSuite | Yes | - | QuickBooks Desktop | Yes | - | QuickBooks Online | Yes | - | Sage Intacct | Yes | - | Xero | 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}/data/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-expenses-api#/schemas/Supplier) for a given company's connection. - - [Suppliers](https://docs.codat.io/sync-for-expenses-api#/schemas/Supplier) are people or organizations that provide something, such as a product or service. - - Before using this endpoint, you must have [retrieved data for the company](https://docs.codat.io/sync-for-expenses-api#/operations/refresh-all-data-types). - - ### Supported Integrations - - | Integration | Supported | - |-------------------------------|-----------| - | Dynamics 365 Business Central | Yes | - | FreeAgent | Yes | - | Oracle NetSuite | Yes | - | QuickBooks Desktop | Yes | - | QuickBooks Online | Yes | - | Sage Intacct | Yes | - | Xero | 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}/data/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 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.UpdateSupplierResponse: - r"""Update supplier - - The *Update supplier* endpoint updates an existing [supplier](https://docs.codat.io/sync-for-expenses-api#/schemas/Supplier) for a given company's connection. - - [Suppliers](https://docs.codat.io/sync-for-expenses-api#/schemas/Supplier) are people or organizations that provide something, such as a product or service. - - **Integration-specific behavior** - - Required data may vary by integration. To see what data to post, first call [Get create/update supplier model](https://docs.codat.io/sync-for-expenses-api#/operations/get-create-update-suppliers-model). - - ### Supported Integrations - - | Integration | Supported | - |-------------------|-----------| - | FreeAgent | Yes | - | QuickBooks Online | Yes | - | Xero | 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.UpdateSupplierRequest) - request = cast(operations.UpdateSupplierRequest, request) - - req = self._build_request( - method="PUT", - path="/companies/{companyId}/connections/{connectionId}/push/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 if request is not None else None, - True, - True, - "json", - OptionalNullable[shared.Supplier], - ), - 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.UpdateSupplierResponse, 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.UpdateSupplierResponse: - r"""Update supplier - - The *Update supplier* endpoint updates an existing [supplier](https://docs.codat.io/sync-for-expenses-api#/schemas/Supplier) for a given company's connection. - - [Suppliers](https://docs.codat.io/sync-for-expenses-api#/schemas/Supplier) are people or organizations that provide something, such as a product or service. - - **Integration-specific behavior** - - Required data may vary by integration. To see what data to post, first call [Get create/update supplier model](https://docs.codat.io/sync-for-expenses-api#/operations/get-create-update-suppliers-model). - - ### Supported Integrations - - | Integration | Supported | - |-------------------|-----------| - | FreeAgent | Yes | - | QuickBooks Online | Yes | - | Xero | 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.UpdateSupplierRequest) - request = cast(operations.UpdateSupplierRequest, request) - - req = self._build_request_async( - method="PUT", - path="/companies/{companyId}/connections/{connectionId}/push/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 if request is not None else None, - True, - True, - "json", - OptionalNullable[shared.Supplier], - ), - 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.UpdateSupplierResponse, 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_expenses.api.suppliers import Suppliers diff --git a/sync-for-expenses/src/codat_sync_for_expenses/sync.py b/sync-for-expenses/src/codat_sync_for_expenses/sync.py index 98bdcbf09..98d37197f 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/sync.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/sync.py @@ -1,793 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.sync — re-export of the sync method group.""" -from .basesdk import BaseSDK -from codat_sync_for_expenses import utils -from codat_sync_for_expenses._hooks import HookContext -from codat_sync_for_expenses.models import errors, operations, shared -from codat_sync_for_expenses.types import BaseModel, OptionalNullable, UNSET -from codat_sync_for_expenses.utils.unmarshal_json_response import ( - unmarshal_json_response, -) -from typing import Any, List, Mapping, Optional, Union, cast - - -class Sync(BaseSDK): - r"""Monitor the status of data syncs.""" - - def get( - self, - *, - request: Union[ - operations.GetSyncByIDRequest, operations.GetSyncByIDRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.CompanySyncStatus: - r"""Get sync status - - Get the sync status for a specified sync - - :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.GetSyncByIDRequest) - request = cast(operations.GetSyncByIDRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/sync/expenses/syncs/{syncId}/status", - 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-sync-by-id", - 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.CompanySyncStatus, 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.GetSyncByIDRequest, operations.GetSyncByIDRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.CompanySyncStatus: - r"""Get sync status - - Get the sync status for a specified sync - - :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.GetSyncByIDRequest) - request = cast(operations.GetSyncByIDRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/sync/expenses/syncs/{syncId}/status", - 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-sync-by-id", - 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.CompanySyncStatus, 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_last_successful_sync( - self, - *, - request: Union[ - operations.GetLastSuccessfulSyncRequest, - operations.GetLastSuccessfulSyncRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.CompanySyncStatus: - r"""Last successful sync - - Gets the status of the last successful sync - - :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.GetLastSuccessfulSyncRequest) - request = cast(operations.GetLastSuccessfulSyncRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/sync/expenses/syncs/lastSuccessful/status", - 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-last-successful-sync", - 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.CompanySyncStatus, 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_last_successful_sync_async( - self, - *, - request: Union[ - operations.GetLastSuccessfulSyncRequest, - operations.GetLastSuccessfulSyncRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.CompanySyncStatus: - r"""Last successful sync - - Gets the status of the last successful sync - - :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.GetLastSuccessfulSyncRequest) - request = cast(operations.GetLastSuccessfulSyncRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/sync/expenses/syncs/lastSuccessful/status", - 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-last-successful-sync", - 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.CompanySyncStatus, 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_latest_sync( - self, - *, - request: Union[ - operations.GetLatestSyncRequest, operations.GetLatestSyncRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.CompanySyncStatus: - r"""Latest sync status - - Gets the latest sync status - - :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.GetLatestSyncRequest) - request = cast(operations.GetLatestSyncRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/sync/expenses/syncs/latest/status", - 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-latest-sync", - 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.CompanySyncStatus, 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_latest_sync_async( - self, - *, - request: Union[ - operations.GetLatestSyncRequest, operations.GetLatestSyncRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.CompanySyncStatus: - r"""Latest sync status - - Gets the latest sync status - - :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.GetLatestSyncRequest) - request = cast(operations.GetLatestSyncRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/sync/expenses/syncs/latest/status", - 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-latest-sync", - 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.CompanySyncStatus, 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 list( - self, - *, - request: Union[ - operations.ListSyncsRequest, operations.ListSyncsRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> List[shared.CompanySyncStatus]: - r"""List sync statuses - - Gets a list of sync statuses - - :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.ListSyncsRequest) - request = cast(operations.ListSyncsRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/sync/expenses/syncs/list/status", - 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-syncs", - 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.CompanySyncStatus], 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 list_async( - self, - *, - request: Union[ - operations.ListSyncsRequest, operations.ListSyncsRequestTypedDict - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> List[shared.CompanySyncStatus]: - r"""List sync statuses - - Gets a list of sync statuses - - :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.ListSyncsRequest) - request = cast(operations.ListSyncsRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/sync/expenses/syncs/list/status", - 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-syncs", - 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.CompanySyncStatus], 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_expenses.api.sync import Sync diff --git a/sync-for-expenses/src/codat_sync_for_expenses/transaction_status.py b/sync-for-expenses/src/codat_sync_for_expenses/transaction_status.py index 6938a60cd..d89e47668 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/transaction_status.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/transaction_status.py @@ -1,407 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.transaction_status — re-export of the transaction_status method group.""" -from .basesdk import BaseSDK -from codat_sync_for_expenses import utils -from codat_sync_for_expenses._hooks import HookContext -from codat_sync_for_expenses.models import errors, operations, shared -from codat_sync_for_expenses.types import BaseModel, OptionalNullable, UNSET -from codat_sync_for_expenses.utils.unmarshal_json_response import ( - unmarshal_json_response, -) -from typing import Any, List, Mapping, Optional, Union, cast - - -class TransactionStatus(BaseSDK): - r"""Monitor the status of individual transactions in data syncs.""" - - def get( - self, - *, - request: Union[ - operations.GetSyncTransactionRequest, - operations.GetSyncTransactionRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> List[shared.SchemaTransaction]: - r"""Get sync transaction - - Gets the status of a transaction for a sync - - :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.GetSyncTransactionRequest) - request = cast(operations.GetSyncTransactionRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/sync/expenses/syncs/{syncId}/transactions/{transactionId}", - 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-sync-transaction", - 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.SchemaTransaction], 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.GetSyncTransactionRequest, - operations.GetSyncTransactionRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> List[shared.SchemaTransaction]: - r"""Get sync transaction - - Gets the status of a transaction for a sync - - :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.GetSyncTransactionRequest) - request = cast(operations.GetSyncTransactionRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/sync/expenses/syncs/{syncId}/transactions/{transactionId}", - 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-sync-transaction", - 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.SchemaTransaction], 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 list( - self, - *, - request: Union[ - operations.ListSyncTransactionsRequest, - operations.ListSyncTransactionsRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Transactions: - r"""List sync transactions - - Gets the transactions and status for a sync - - :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.ListSyncTransactionsRequest) - request = cast(operations.ListSyncTransactionsRequest, request) - - req = self._build_request( - method="GET", - path="/companies/{companyId}/sync/expenses/syncs/{syncId}/transactions", - 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-sync-transactions", - 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.Transactions, 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.ListSyncTransactionsRequest, - operations.ListSyncTransactionsRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.Transactions: - r"""List sync transactions - - Gets the transactions and status for a sync - - :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.ListSyncTransactionsRequest) - request = cast(operations.ListSyncTransactionsRequest, request) - - req = self._build_request_async( - method="GET", - path="/companies/{companyId}/sync/expenses/syncs/{syncId}/transactions", - 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-sync-transactions", - 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.Transactions, 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_expenses.api.transaction_status import TransactionStatus diff --git a/sync-for-expenses/src/codat_sync_for_expenses/transfers.py b/sync-for-expenses/src/codat_sync_for_expenses/transfers.py index 47ee0b46c..297f8bb2f 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/transfers.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/transfers.py @@ -1,261 +1,3 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.transfers — re-export of the transfers method group.""" -from .basesdk import BaseSDK -from codat_sync_for_expenses import utils -from codat_sync_for_expenses._hooks import HookContext -from codat_sync_for_expenses.models import errors, operations, shared -from codat_sync_for_expenses.types import BaseModel, OptionalNullable, UNSET -from codat_sync_for_expenses.utils.unmarshal_json_response import ( - unmarshal_json_response, -) -from typing import Any, Mapping, Optional, Union, cast - - -class Transfers(BaseSDK): - r"""Create and update transactions that represent the movement of your customers' money.""" - - def create( - self, - *, - request: Union[ - operations.CreateTransferTransactionRequest, - operations.CreateTransferTransactionRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.TransferTransactionResponse: - r"""Create transfer transaction - - Use the *Create transfer* endpoint to create or update a [transfer transaction](https://docs.codat.io/sync-for-expenses-api#/schemas/TransferTransactionRequest) in the accounting software for a given company's connection. - - Transfers record the movement of money between two bank accounts, or between a bank account and a nominal account. Use them to represent actions such as topping up a debit card account or a balance transfer to another credit card. - - The `from.amount` and `to.amount` fields are in the native currency of the account. - - ### Supported Integrations - | Integration | Create transfer | Update transfer | - |-----------------------|------------------|------------------| - | Dynamics | No | No | - | FreeAgent | Yes | Yes | - | NetSuite | No | No | - | QuickBooks Desktop | Yes | No | - | QuickBooks Online | Yes | Yes | - | Sage Intacct | No | No | - | Xero | Yes | No | - | Zoho Books | No | 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.CreateTransferTransactionRequest - ) - request = cast(operations.CreateTransferTransactionRequest, request) - - req = self._build_request( - method="PUT", - path="/companies/{companyId}/sync/expenses/transfer-transactions/{transactionId}", - 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.transfer_transaction_request if request is not None else None, - False, - True, - "json", - Optional[shared.TransferTransactionRequest], - ), - 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-transfer-transaction", - 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.TransferTransactionResponse, 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.CreateTransferTransactionRequest, - operations.CreateTransferTransactionRequestTypedDict, - ], - retries: OptionalNullable[utils.RetryConfig] = UNSET, - server_url: Optional[str] = None, - timeout_ms: Optional[int] = None, - http_headers: Optional[Mapping[str, str]] = None, - ) -> shared.TransferTransactionResponse: - r"""Create transfer transaction - - Use the *Create transfer* endpoint to create or update a [transfer transaction](https://docs.codat.io/sync-for-expenses-api#/schemas/TransferTransactionRequest) in the accounting software for a given company's connection. - - Transfers record the movement of money between two bank accounts, or between a bank account and a nominal account. Use them to represent actions such as topping up a debit card account or a balance transfer to another credit card. - - The `from.amount` and `to.amount` fields are in the native currency of the account. - - ### Supported Integrations - | Integration | Create transfer | Update transfer | - |-----------------------|------------------|------------------| - | Dynamics | No | No | - | FreeAgent | Yes | Yes | - | NetSuite | No | No | - | QuickBooks Desktop | Yes | No | - | QuickBooks Online | Yes | Yes | - | Sage Intacct | No | No | - | Xero | Yes | No | - | Zoho Books | No | 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.CreateTransferTransactionRequest - ) - request = cast(operations.CreateTransferTransactionRequest, request) - - req = self._build_request_async( - method="PUT", - path="/companies/{companyId}/sync/expenses/transfer-transactions/{transactionId}", - 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.transfer_transaction_request if request is not None else None, - False, - True, - "json", - Optional[shared.TransferTransactionRequest], - ), - 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-transfer-transaction", - 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.TransferTransactionResponse, 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_expenses.api.transfers import Transfers diff --git a/sync-for-expenses/src/codat_sync_for_expenses/types/__init__.py b/sync-for-expenses/src/codat_sync_for_expenses/types/__init__.py index fc76fe0c5..a5e7b8709 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/types/__init__.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/types/__init__.py @@ -1,21 +1,52 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" - -from .basemodel import ( - BaseModel, - Nullable, - OptionalNullable, - UnrecognizedInt, - UnrecognizedStr, - UNSET, - UNSET_SENTINEL, -) - -__all__ = [ - "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-expenses/src/codat_sync_for_expenses/types/basemodel.py b/sync-for-expenses/src/codat_sync_for_expenses/types/basemodel.py deleted file mode 100644 index a9a640a1a..000000000 --- a/sync-for-expenses/src/codat_sync_for_expenses/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-expenses/src/codat_sync_for_expenses/utils/__init__.py b/sync-for-expenses/src/codat_sync_for_expenses/utils/__init__.py index 0498cb8da..bc29c91b8 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/utils/__init__.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/utils/__init__.py @@ -1,175 +1,5 @@ -"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" +"""codat_sync_for_expenses.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-expenses/src/codat_sync_for_expenses/utils/annotations.py b/sync-for-expenses/src/codat_sync_for_expenses/utils/annotations.py deleted file mode 100644 index 12e0aa4f1..000000000 --- a/sync-for-expenses/src/codat_sync_for_expenses/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-expenses/src/codat_sync_for_expenses/utils/datetimes.py b/sync-for-expenses/src/codat_sync_for_expenses/utils/datetimes.py deleted file mode 100644 index a6c52cd61..000000000 --- a/sync-for-expenses/src/codat_sync_for_expenses/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-expenses/src/codat_sync_for_expenses/utils/dynamic_imports.py b/sync-for-expenses/src/codat_sync_for_expenses/utils/dynamic_imports.py deleted file mode 100644 index 673edf82a..000000000 --- a/sync-for-expenses/src/codat_sync_for_expenses/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-expenses/src/codat_sync_for_expenses/utils/enums.py b/sync-for-expenses/src/codat_sync_for_expenses/utils/enums.py deleted file mode 100644 index 3324e1bc2..000000000 --- a/sync-for-expenses/src/codat_sync_for_expenses/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-expenses/src/codat_sync_for_expenses/utils/eventstreaming.py b/sync-for-expenses/src/codat_sync_for_expenses/utils/eventstreaming.py deleted file mode 100644 index 3bdcd6d3d..000000000 --- a/sync-for-expenses/src/codat_sync_for_expenses/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-expenses/src/codat_sync_for_expenses/utils/forms.py b/sync-for-expenses/src/codat_sync_for_expenses/utils/forms.py deleted file mode 100644 index f961e76be..000000000 --- a/sync-for-expenses/src/codat_sync_for_expenses/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-expenses/src/codat_sync_for_expenses/utils/headers.py b/sync-for-expenses/src/codat_sync_for_expenses/utils/headers.py deleted file mode 100644 index 37864cbbb..000000000 --- a/sync-for-expenses/src/codat_sync_for_expenses/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-expenses/src/codat_sync_for_expenses/utils/logger.py b/sync-for-expenses/src/codat_sync_for_expenses/utils/logger.py deleted file mode 100644 index b661aff65..000000000 --- a/sync-for-expenses/src/codat_sync_for_expenses/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-expenses/src/codat_sync_for_expenses/utils/metadata.py b/sync-for-expenses/src/codat_sync_for_expenses/utils/metadata.py deleted file mode 100644 index 5abddd588..000000000 --- a/sync-for-expenses/src/codat_sync_for_expenses/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-expenses/src/codat_sync_for_expenses/utils/queryparams.py b/sync-for-expenses/src/codat_sync_for_expenses/utils/queryparams.py deleted file mode 100644 index c04e0db82..000000000 --- a/sync-for-expenses/src/codat_sync_for_expenses/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-expenses/src/codat_sync_for_expenses/utils/requestbodies.py b/sync-for-expenses/src/codat_sync_for_expenses/utils/requestbodies.py deleted file mode 100644 index 1de32b6d2..000000000 --- a/sync-for-expenses/src/codat_sync_for_expenses/utils/requestbodies.py +++ /dev/null @@ -1,66 +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-expenses/src/codat_sync_for_expenses/utils/retries.py b/sync-for-expenses/src/codat_sync_for_expenses/utils/retries.py index af07d4e94..28b22e85e 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/utils/retries.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/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-expenses/src/codat_sync_for_expenses/utils/security.py b/sync-for-expenses/src/codat_sync_for_expenses/utils/security.py deleted file mode 100644 index 42d8d78e9..000000000 --- a/sync-for-expenses/src/codat_sync_for_expenses/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-expenses/src/codat_sync_for_expenses/utils/serializers.py b/sync-for-expenses/src/codat_sync_for_expenses/utils/serializers.py index d2149f8b9..9135d0666 100644 --- a/sync-for-expenses/src/codat_sync_for_expenses/utils/serializers.py +++ b/sync-for-expenses/src/codat_sync_for_expenses/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_expenses.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-expenses/src/codat_sync_for_expenses/utils/unmarshal_json_response.py b/sync-for-expenses/src/codat_sync_for_expenses/utils/unmarshal_json_response.py deleted file mode 100644 index 485351526..000000000 --- a/sync-for-expenses/src/codat_sync_for_expenses/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_expenses.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-expenses/src/codat_sync_for_expenses/utils/url.py b/sync-for-expenses/src/codat_sync_for_expenses/utils/url.py deleted file mode 100644 index c78ccbae4..000000000 --- a/sync-for-expenses/src/codat_sync_for_expenses/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-expenses/src/codat_sync_for_expenses/utils/values.py b/sync-for-expenses/src/codat_sync_for_expenses/utils/values.py deleted file mode 100644 index dae01a443..000000000 --- a/sync-for-expenses/src/codat_sync_for_expenses/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) diff --git a/sync-for-expenses/src/codatsyncexpenses/_hooks/registration.py b/sync-for-expenses/src/codatsyncexpenses/_hooks/registration.py deleted file mode 100644 index 1db6a5293..000000000 --- a/sync-for-expenses/src/codatsyncexpenses/_hooks/registration.py +++ /dev/null @@ -1,13 +0,0 @@ -from .types import Hooks - - -# This file is only ever generated once on the first generation and then is free to be modified. -# Any hooks you wish to add should be registered in the init_hooks function. Feel free to define them -# in this file or in separate files in the hooks folder. - - -def init_hooks(hooks: Hooks): - # pylint: disable=unused-argument - """Add hooks by calling hooks.register{sdk_init/before_request/after_success/after_error}Hook - with an instance of a hook that implements that specific Hook interface - Hooks are registered per SDK instance, and are valid for the lifetime of the SDK instance"""